我想计算每一行中包含特定字符串的单元格的数量,该特定字符串超过一次的单元格应该只计算一次。
我可以计算一行中等于给定值的单元格的数量,但是当我扩展此逻辑以使用str.contains时,我遇到了问题,如下所示
d = {'col1': ["a#", "b","c#"], 'col2': ["a", "b","c#"]}
df = pd.DataFrame(d)
#can correctly count across rows using equality
thisworks =( df =="a#" ).sum(axis=1)
#can count across a column using str.contains
thisworks1=df['col1'].str.contains('#').sum()
#but cannot use str.contains with a dataframe so what is the alternative
thisdoesnt =( df.str.contains('#') ).sum(axis=1)
输出应该是一个序列,显示包含给定字符串的每行中的单元格数量。
发布于 2019-05-29 08:12:04
使用df.apply
的解决方案
df = pd.DataFrame({'col1': ["a#", "b","c#"],
'col2': ["a", "b","c#"]})
df
col1 col2
0 a# a
1 b b
2 c# c#
df['sum'] = df.apply(lambda x: x.str.contains('#'), axis=1).sum(axis=1)
col1 col2 sum
0 a# a 1
1 b b 0
2 c# c# 2
发布于 2019-05-29 07:58:04
像这样的东西应该是有效的:
df = pd.DataFrame({'col1': ['#', '0'], 'col2': ['#', '#']})
df['totals'] = df['col1'].str.contains('#', regex=False).astype(int) +\
df['col2'].str.contains('#', regex=False).astype(int)
df
# col1 col2 totals
# 0 # # 2
# 1 0 # 1
它应该泛化到您想要的任意数量的列。
https://stackoverflow.com/questions/56351383
复制相似问题