pandas :在所有列中都计入一定价值 [英] Pandas: count some value in all columns

查看:64
本文介绍了 pandas :在所有列中都计入一定价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框

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"的计数.
所需的输出:

I need to get the count of the value 'blue' of every string/line.
The desired output:

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')

推荐答案

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

这篇关于 pandas :在所有列中都计入一定价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆