我有一个df
,
inv_id
W/E FEB 8 2017
W/E JAN 24 2018
W/E MAR 11 18
W/E APR 09 17
2018 Q1
2011 Q2
inv_id
的值都是字符串。这些值具有以下格式 ( strftime
),
%b %d %Y
%b %d %y
%b %d(non zero padded) %Y
%b %d(non zero padded) %y
%Y Q\d(regex decimal)
我在 strftime
中找不到一个月中非零填充天数的指令.
我想知道如何定义模式并使用 pandas
识别它们,也许pandas.Series.str.contains
?所以结果看起来像,
inv_id is_date
W/E FEB 8 2017 True
W/E JAN 24 2018 True
W/E MAR 11 18 True
W/E APR 09 17 True
2018 Q1 True
2011 Q2 True
更新。设法处理第二种情况,
df['inv_id'].str.contains(pat=r'\b(19|20)\d{2} Q\d{1}\b', regex=True)
最佳答案
您可能会完全疯狂,使用更新的 regex
模块并利用子例程。
在这里,我们可以首先想到简单的砖 block ,然后将它们以可能的格式粘合在一起(名为 format1
, format2
, ... formatn
我)。
看看这段可爱的代码:
(?(DEFINE)
(?<month>JAN|FEB|MAR|APR)
(?<day>\b\d{1,2}\b)
(?<year>\b[12]\d{3}\b)
(?<year_short>\b[012]\d\b)
(?<quarter>Q[1234])
(?<ws>\s*)
# here comes the fun part
(?<format1>(?&month)(?&ws)(?&day)(?&ws)(?:(?&year)|(?&year_short)))
(?<format2>(?&year)(?&ws)(?&quarter))
# check for any existance
(?<formats>(?&format1)|(?&format2))
)
^(?=.*?(?&formats))
和a demo on regex101.com 。这需要通过应用函数进行检查:
def check_format(string):
if re.search(pattern, string):
return True
return False
df['is_date'] = df['inv_id'].apply(check_format)
最后你可能会得到:
import pandas as pd, regex as re
d = {'inv_id': ['W/E FEB 8 2017', 'W/E JAN 24 2018', 'W/E MAR 11 18', 'W/E APR 09 17', '2018 Q1', '2011 Q2', 'somejunk', 'garbage in here']}
df = pd.DataFrame(d)
rx = re.compile(r'''the pattern from above''', re.VERBOSE)
def check_format(string):
return True if rx.search(string) else False
df['is_date'] = df['inv_id'].apply(check_format)
print(df)
这会产生
inv_id is_date
0 W/E FEB 8 2017 True
1 W/E JAN 24 2018 True
2 W/E MAR 11 18 True
3 W/E APR 09 17 True
4 2018 Q1 True
5 2011 Q2 True
6 somejunk False
7 garbage in here False
关于python - pandas如何识别具有特定模式的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54988359/