如何解决提取所有以'st','nd','rd','th'结尾的日期,同时使用RegEx将日期与月份交换
我在pandas数据框列的文本中输入了这些日期。
import pandas as pd
sr = pd.Series(['text Mar 20,2009 text','text march 20,'text 20 Mar. 2009 text','text Sep 2010 text','text Mar 20th,2009 text ','text Mar 21st,2009 text'])
当我使用正则表达式时,会得到这个。
a=sr.str.extractall(r'((?P<day>(?:\d{2} )?(?P<month>(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*)) (?:\d{2}[-/th|st|nd|rd\s]*[,.]* )?(?P<year>\d{4}))')
all day month year
match
0 0 Mar 20,2009 Mar Mar 2009
1 0 march 20,2009 march march 2009
2 0 20 Mar. 2009 20 Mar. Mar. 2009
3 0 Sep 2010 Sep Sep 2010
4 0 Mar 20th,2009 Mar Mar 2009
5 0 Mar 21st,2009 Mar Mar 2009
如何将日期(20、20、21st ...)放入“天”列?
解决方法
使用熊猫的一种解决方案(为什么要重新发明轮子?)
import pandas as pd
df = sr.to_frame(name='all')
df['all'] = pd.to_datetime(df['all'])
df['day'] = df['all'].dt.day
df['month'] = df['all'].dt.strftime('%b')
df['year'] = df['all'].dt.year
输出:
all day month year
0 2009-03-20 20 Mar 2009
1 2009-03-20 20 Mar 2009
2 2009-03-20 20 Mar 2009
3 2010-09-01 1 Sep 2010
4 2009-03-20 20 Mar 2009
5 2009-03-21 21 Mar 2009
,
也许另一种解决方案可能是使用PyPi regex module和分支重置组(?|
来匹配日期和月份。
没有命名组的模式:
\b((?|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*(?: (\d{2}(?:th|st|nd|rd)?)?[,.])?|(\d{2}) (?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*)?) (\d{4}))
import pandas as pd
import regex
pattern = r"\b(?P<all>(?|(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*(?: (?P<day>\d{2}(?:th|st|nd|rd)?)?[,.])?|(?P<day>\d{2}) (?:(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z,.]*)?) (?P<year>\d{4}))"
items = [
'text Mar 20,2009 text','text March 20,'text 20 Mar. 2009 text','text Sep 2010 text','text Mar 20th,2009 text ','text Mar 21st,2009 text'
]
res = map(lambda x: regex.findall(pattern,x)[0],items)
df = pd.DataFrame(res)
df.columns = ['all','month','day','year']
print(df)
输出
all month day year
0 Mar 20,2009 Mar 20 2009
1 March 20,2009 Mar 20 2009
2 20 Mar. 2009 Mar 20 2009
3 Sep 2010 Sep 2010
4 Mar 20th,2009 Mar 20th 2009
5 Mar 21st,2009 Mar 21st 2009
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。