python - pandas如何识别具有特定模式的字符串

标签 python regex python-3.x pandas

我有一个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/

相关文章:

python - 如何只引用MultiIndex的某些部分?

python - 获取 socket.gaierror : [Errno 8] nodename nor servname provided, 或未知

php - 从 PHP 字符串中删除除字母以外的所有内容

python - 通过 termios.TIOCSTI 注入(inject) unicode 字符

python - 有没有办法在python中使用字典输入一个字符串并使用键输出另一个字符串?

c++ - 基准测试(python 与使用 BLAS 的 c++)和(numpy)

python - 在python中使用正则表达式从文本中删除html标签

javascript - 正则表达式循环问题

C 扩展在 Python 3.7 中不起作用说 ImportError : dynamic module does not define module export function (PyInit_loop)

python - 如何检查函数来自哪个模块?