pandas 计算pandas/python中df列中非零数字的数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34968223/
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-09-14 00:33:33  来源:igfitidea点击:

counting the number of non-zero numbers in a column of a df in pandas/python

pythonnumpypandas

提问by user5826447

I have a df that looks something like:

我有一个 df 看起来像:

a b c d e 0 1 2 3 5 1 4 0 5 2 5 8 9 6 0 4 5 0 0 0

a b c d e 0 1 2 3 5 1 4 0 5 2 5 8 9 6 0 4 5 0 0 0

I would like to output the number of numbers in column c that are not zero. Any help would be really appreciated!

我想输出 c 列中不为零的数字数量。任何帮助将非常感激!

回答by jezrael

Use double sum:

使用双sum

print df
   a  b  c  d  e
0  0  1  2  3  5
1  1  4  0  5  2
2  5  8  9  6  0
3  4  5  0  0  0

print (df != 0).sum(1)
0    4
1    4
2    4
3    2
dtype: int64

print (df != 0).sum(1).sum()
14

If you need count only column cor d:

如果您只需要计算列cd

print (df['c'] != 0).sum()
2

print (df['d'] != 0).sum()
3

EDIT: Solution with numpy.sum:

编辑:解决方案numpy.sum

print ((df != 0).values.sum())
14

回答by Stig Johan B.

Numpy's count_nonzerofunction is efficient for this.

Numpy 的count_nonzero功能对此非常有效。

np.count_nonzero(df["c"])

np.count_nonzero(df["c"])