[英]Extract and sort dates from Python dataframe using regex
我正在研究单列pandas数据帧,包含数千(行)的字符串表达式。 每个字符串可能包含不同格式的“日期”信息,例如:
05/10/2001; 05/10/01; 5/10/09; 6/2/01
May-10-2001; May 10, 2010; March 25, 2001; Mar. 25, 2001; Mar 25 2001;
25 Mar 2001; 25 March 2001; 25 Mar. 2001; 25 March, 2001
Mar 25th, 2001; Mar 25th, 2001; Mar 12nd, 2001
Feb 2001; Sep 2001; Oct 2001
5/2001; 11/2001
2001; 2015
要使用几个字符串作为示例:
df[0] he plans to depart on 6/12/95 df[1] as of Mar. 23rd, 2011, the board decides that... df[2] the 12-28-01 record shows...
我想在df之后使用findall()函数,这样df.str.findall(r'')就会提取日期元素:
[0] 6/12/95 [1] Mar. 23rd, 2011 [2] 12-28-01
从原始字符串开始,然后是一些'sort'命令行,按照时间顺序按提取的日期对它们的索引进行排序,这样输出应该看起来像
[0] 1 [1] 3 [2] 2
我(暂时)使用以下功能
df.str.findall(r'(?:\\d{2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[az]* (?:\\d{2}, )?\\d{4}')
但不知道如何处理
(1)数字后的序数指示符:st,th,nd
(2)偶尔“。” 表示缩写的值,和
(3)斜杠(/)和连字符( - )
一次性使用正则表达式最终函数。
此外,在完成所有提取工作之后,我想按时间顺序对它们各自的索引(即1,2,3,...,n)进行排序。 但是我目前对正则表达式的了解不足以知道Python如何按时间顺序对这些不同的日期格式进行排序。
如果有人可以在.findall()函数上使用一些方便的技巧来启发我,或者解释用于排序日期表达式的机制,将会非常感激。
dateutil.parser.parse
可以帮助你避免正则表达式 - 这肯定是一件好事。
它基本上需要一个字符串并尝试在datetime
对象中解析它,这很好,因为datetime
可以很容易地排序。
from dateutil.parser import parse
data = """05/10/2001; 05/10/01; 5/10/09; 6/2/01
May-10-2001; May 10, 2010; March 25, 2001; Mar. 25, 2001; Mar 25 2001;
25 Mar 2001; 25 March 2001; 25 Mar. 2001; 25 March, 2001
Mar 25th, 2001; Mar 25th, 2001; Mar 12nd, 2001
Feb 2001; Sep 2001; Oct 2001
5/2001; 11/2001
2001; 2015"""
# Parse data into list of strings
data = data.replace('\n', ';').split(';')
dates = []
for line in data:
try:
dates.append(parse(line))
except TypeError:
# it's not parsable
pass
print list(sorted(dates))
切割输出:
[datetime.datetime(2001, 2, 4, 0, 0), datetime.datetime(2001, 3, 12, 0, 0), datetime.datetime(2001, 3, 25, 0, 0), datetime.datetime(2001, 3, 25, 0, 0) ...]
你可以看到你在两点上获胜:
parse
为您执行此操作 我会尝试使用以下两个模块。 dateutil在这个答案中:
和/或日期分析员:
试试这个“”“(r'(?:\\ d {1,2} [] [/ - ] )?(?:(?:Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | 10月| 11月| 12月)[az] *)?(?:\\ d {1,2} [/ - ])?\\ d {2,4}')“”“
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.