[英]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.