DataFrame 包含一列具有以下类型的日期:“'5-15-2019'”并且 05152021.I 想要提取它的模式
DataFrame contains a column of dates which are having these types: "'5-15-2019'" and 05152021.I want to extract pattern of it
DataFrame 包含具有以下类型的日期:“21-10-2021”并且 29052021.I 想要提取它的模式。
例如'5-15-2019',它需要产生'%d-%m-%Y'
'05152021' 它需要生成 '%d%m%Y'
我这样试过:
search6=[]
for val in list(df.apply(lambda x:re.search('(?:[1-9]|[12][0-9]|3[01])[-](?:[1-9]|10|11|12])[-]\d{2,4}',str(x)))):
if val:
li=val.group()
search6.append(li)
print(search6)
输出:我得到了那些 patterns.i 需要获取模式 '%d-%m-%Y' 的列表,同样我需要获取 '%d%m%Y' 的模式 also.how 我需要这样做吗?任何人都可以帮助 me.Thank 你
您可以使用内部 pandas 方法 pandas._libs.tslibs.parsing.guess_datetime_format
。请注意,这不是 public API 的一部分,因此该功能将来可能会在没有任何警告的情况下更改。
选项 1
from pandas._libs.tslibs.parsing import guess_datetime_format
s = pd.Series(['21-10-2021', '29052021', '5-15-2019', '05152021', '20000101', '01-01-2001'])
s.map(lambda x: guess_datetime_format(x, dayfirst=True))
选项 2
....YYYY
日期不受支持。对于那些你需要通过临时添加破折号来作弊的人:
def parse(x):
out = guess_datetime_format(x, dayfirst=True)
if out is None and x.isdigit() and len(x)==8:
out = (guess_datetime_format(f'{x[:2]}-{x[2:4]}-{x[4:]}',
dayfirst=True)
.replace('-', '')
)
return out
s.map(parse)
示例:
date option1 option2
0 21-10-2021 %d-%m-%Y %d-%m-%Y
1 29052021 None %d%m%Y
2 5-15-2019 %m-%d-%Y %m-%d-%Y
3 05152021 None %m%d%Y
4 20000101 %Y%m%d %Y%m%d
5 01-01-2001 %d-%m-%Y %d-%m-%Y
DataFrame 包含具有以下类型的日期:“21-10-2021”并且 29052021.I 想要提取它的模式。 例如'5-15-2019',它需要产生'%d-%m-%Y' '05152021' 它需要生成 '%d%m%Y'
我这样试过:
search6=[]
for val in list(df.apply(lambda x:re.search('(?:[1-9]|[12][0-9]|3[01])[-](?:[1-9]|10|11|12])[-]\d{2,4}',str(x)))):
if val:
li=val.group()
search6.append(li)
print(search6)
输出:我得到了那些 patterns.i 需要获取模式 '%d-%m-%Y' 的列表,同样我需要获取 '%d%m%Y' 的模式 also.how 我需要这样做吗?任何人都可以帮助 me.Thank 你
您可以使用内部 pandas 方法 pandas._libs.tslibs.parsing.guess_datetime_format
。请注意,这不是 public API 的一部分,因此该功能将来可能会在没有任何警告的情况下更改。
选项 1
from pandas._libs.tslibs.parsing import guess_datetime_format
s = pd.Series(['21-10-2021', '29052021', '5-15-2019', '05152021', '20000101', '01-01-2001'])
s.map(lambda x: guess_datetime_format(x, dayfirst=True))
选项 2
....YYYY
日期不受支持。对于那些你需要通过临时添加破折号来作弊的人:
def parse(x):
out = guess_datetime_format(x, dayfirst=True)
if out is None and x.isdigit() and len(x)==8:
out = (guess_datetime_format(f'{x[:2]}-{x[2:4]}-{x[4:]}',
dayfirst=True)
.replace('-', '')
)
return out
s.map(parse)
示例:
date option1 option2
0 21-10-2021 %d-%m-%Y %d-%m-%Y
1 29052021 None %d%m%Y
2 5-15-2019 %m-%d-%Y %m-%d-%Y
3 05152021 None %m%d%Y
4 20000101 %Y%m%d %Y%m%d
5 01-01-2001 %d-%m-%Y %d-%m-%Y