Python 计算熊猫列中 False 或 True 的出现次数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53550988/
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
Count occurrences of False or True in a column in pandas
提问by Ney J Torres
given
给予
patient_id test_result has_cancer
0 79452 Negative False
1 81667 Positive True
2 76297 Negative False
3 36593 Negative False
4 53717 Negative False
5 67134 Negative False
6 40436 Negative False
how to count False or True in a column , in python?
如何在python中计算列中的False或True?
I had been trying:
我一直在尝试:
# number of patients with cancer
number_of_patients_with_cancer= (df["has_cancer"]==True).count()
print(number_of_patients_with_cancer)
回答by YOBEN_S
So you need value_counts
?
所以你需要value_counts
?
df.has_cancer.value_counts()
Out[345]:
False 6
True 1
Name: has_cancer, dtype: int64
回答by cs95
If has_cancer
has NaNs:
如果has_cancer
有 NaN:
false_count = (~df.has_cancer).sum()
If has_cancer
does not have NaNs, you can optimise by not having to negate the masks beforehand.
如果has_cancer
没有 NaN,您可以通过不必事先否定掩码来进行优化。
false_count = len(df) - df.has_cancer.sum()
And similarly, if you want justthe count of True values, that's
同样,如果您只想要True 值的计数,那就是
true_count = df.has_cancer.sum()
if you want both, it is
如果你想要两个,那就是
fc, tc = df.has_cancer.value_counts().sort_index().tolist()
回答by David Miller
0 True
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
If the panda series above is called example
如果上面的熊猫系列被称为示例
example.sum()
Then this code outputs 1 since there is only one True
value in the series. To get the count of False
然后此代码输出 1,因为True
该系列中只有一个值。得到计数False
len(example) - example.sum()
回答by garima5aqua
number_of_patients_with_cancer = df.has_cancer[df.has_cancer==True].count()
回答by gilch
Just sum the column for a count of the Trues. False is just a special case of 0 and True a special case of 1. The False count would be your row count minus that. Unless you've got na
's in there.
只需将列相加即可获得 True 的计数。False 只是 0 的特例,True 是 1 的特例。 False 计数将是您的行计数减去它。除非你na
在那里。