【问题标题】:Pandas: count some value in all columns熊猫:计算所有列中的一些值
【发布时间】:2017-04-02 18:40:06
【问题描述】:

我有一个数据框

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

我需要获取每个字符串/行的值“蓝色”的计数。
所需的输出:

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      带着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
      

      幼稚时间测试

      【讨论】:

        【解决方案3】:

        根据pandas.DataFrame.eq

        获取数据框和其他元素的等于(二元运算符 eq)。

        在灵活的包装器(eqneleltgegt)和比较运算符之间。

        相当于 ==、=!、=、>,支持选择轴(行或列)和级别进行比较。

        不只是用于数字。

        希望这些信息对您有所帮助

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-13
          • 1970-01-01
          相关资源
          最近更新 更多