使用str 处理文本函数,使用str[0] 处理字符串的第一个值,最后一个sum 处理计数Trues 值:
mask= ((analytic_events['section']==2) &
~(analytic_events['identifier'].str[0].str.isdigit()))
print (mask.sum())
如果性能很重要并且没有缺失值,则使用列表推导:
arr = ~np.array([x[0].isdigit() for x in analytic_events['identifier']])
mask = ((analytic_events['section']==2) & arr)
编辑:
为什么我的过滤器会通过所有行,而不仅仅是那些标识符不以数字开头的行?
如果你的解决方案的测试输出:
analytic_events = pd.DataFrame(
{'section':[2,2,2,3,2],
'identifier':['4hj','8hj','gh','th','h6h']})
print (analytic_events)
section identifier
0 2 4hj
1 2 8hj
2 2 gh
3 3 th
4 2 h6h
获取列的第一个值:
print ((analytic_events['identifier'][0]))
4hj
检查标量的位数:
print ((analytic_events['identifier'][0].isdigit()))
False
print (~(analytic_events['identifier'][0].isdigit()))
-1
使用带有第一个掩码的链将其转换为True:
print ((analytic_events['section']==2) & ~(analytic_events['identifier'][0].isdigit()))
0 True
1 True
2 True
3 False
4 True
Name: section, dtype: bool
所以它的工作原理与不存在第二个掩码一样:
print (analytic_events['section']==2)
0 True
1 True
2 True
3 False
4 True
Name: section, dtype: bool