python - 无法对与 pandas/python 中的正则表达式匹配的行求和

标签 python regex pandas

我可以找到 pandas 数据框中一列中不遵循某种模式的行数,但找不到遵循完全相同模式的行数!

这个有效:

df.report_date.apply(lambda x: (not re.match(r'[0-9]{4}-[0-9]{1,2}-[0-9]{1 ,2}', x))).sum()

这不会:删除“not”不会告诉我有多少行匹配,但会引发 TypeError。知道为什么会这样吗? df.report_date.apply(lambda x: (re.match(r'[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}', x) )).sum()

最佳答案

df = pd.DataFrame(dict(
       report_date=[
           '2001-02-04',
           '2016-11-12',
           '1-1-1999',
           '02-28-2012',
           '1995-09-30'
        ]
    ))
df

enter image description here


regex = r'[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}'
print('does match:    {}\ndoesn\'t match: {}'.format(
        df.report_date.str.match(regex).sum(),
        df.report_date.str.match(regex).__neg__().sum()
    ))

does match:    3
doesn't match: 2

regex = r'[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}'
df.groupby(df.report_date.str.match(regex)).size()

report_date
False    2
True     3
dtype: int64

关于python - 无法对与 pandas/python 中的正则表达式匹配的行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40309777/

相关文章:

python - 无法对拆卸中的异常使用react

python - 在 PyQt 中的菜单栏下方显示图像

javascript - 匹配整行,对序列中所有出现的地方以及中间的所有内容进行分组

regex - 如何在perl中提取用单引号括起来的字符串?

用于检查日期的 PHP 正则表达式为 YYYY-MM-DD 格式

python - 分配一个 pandas dataframe NULL=0, non-NULLvalue=1

python - 在 pandas 数据框中创建新列取决于同一数据框中但不同行中的其他列

python - 通过不同的 TCP 端口回显通过 UDP 接收的消息

python - 重采样时每天保留24h `pandas` `Series`(从每天到每小时)

python - 使用pandas read_stata() 函数时汉字都变成乱码