Pandas:计算所有列中某个值的数量

4

我有一个数据框

graph   0       1       2       3       4
1       blue    blue    blue    blue    blue
2       blue    blue    blue    blue    blue
3       blue    red     blue    blue    red
4       red     blue    red     red     blue
5       red     red     blue    red     red
6       blue    blue    blue    blue    blue

我需要获取每个字符串/行中值为“blue”的计数。
期望的输出结果:
graph   result
1       5
2       5
3       3
4       2
5       1
6       5

我尝试使用以下方法进行操作:

(df['0', '1', '2', '3', '4']).applymap(lambda x: str.count(x, 'blue'))

但它返回的是:
KeyError: ('0', '1', '2', '3', '4')
3个回答

3
In [35]: df.set_index('graph').eq('blue').sum(1).reset_index(name='result')
Out[35]:
   graph  result
0      1       5
1      2       5
2      3       3
3      4       2
4      5       1
5      6       5

1
根据 pandas.DataFrame.eq
获取数据框和其他数据的相等值,逐个元素进行比较(二进制运算符eq)。
它是灵活包装器(eqneleltgegt)中的一种,用于比较运算符。
相当于==、=!、<=、<、>=、>,并支持选择轴(行或列)和级别进行比较。
不仅适用于数字。
希望这些信息有所帮助。

1
numpy 为基础。如果您可靠地知道 graph 列在哪里,即第 0 列,请从头开始重建。
v = df.values
pd.DataFrame(dict(graph=v[:, 0], result=(df.values[:, 1:] == 'blue').sum(1)))

  graph  result
0     1       5
1     2       5
2     3       3
3     4       2
4     5       1
5     6       5

"naive time test"
enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接