Python 在熊猫数据框中按列计算数字的出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27140860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:28:33  来源:igfitidea点击:

count occurrences of number by column in pandas data frame

pythonpandas

提问by Erich

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

我有一个 Pandas 数据框,我想计算每列数字在列中出现的频率

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

This is my code that does not work

这是我的代码不起作用

def equalsOne(x):
    x[x.columns == 1].sum()

df1.apply(equalOne(), axis = 1)

Here is the desired output

这是所需的输出

a 2
b 0
c 3
d 0
e 0 

采纳答案by Daniel Velkov

You can do:

你可以做:

(df==1).sum()

df==1gives:

df==1给出:

       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 Falseas 0and Trueas 1.

sum()对待False作为0True作为1

回答by Bob Haffner

This should do the trick

这应该可以解决问题

df1[df1 == 1].count()