我可以找到 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
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/