count occurrences of number by column in pandas data frame

前端 未结 2 1728
悲哀的现实
悲哀的现实 2020-12-31 10:26

I have a pandas data frame I want to count how often a number appears in a column for each column

     a   b   c   d   e
0    2   3   1   5   4
1    1   3            


        
相关标签:
2条回答
  • 2020-12-31 10:49

    You can do:

    (df==1).sum()
    

    df==1 gives:

           a      b      c      d      e
    0  False  False   True  False  False
    1   True  False  False  False  False
    2   True  False  False  False  False
    3  False  False   True  False  False
    4  False  False   True  False  False
    

    and the sum() treats False as 0 and True as 1.

    0 讨论(0)
  • 2020-12-31 10:54

    This should do the trick

    df1[df1 == 1].count()
    
    0 讨论(0)
提交回复
热议问题