[英]Count True/False occurences across dataframe (columns & rows)
I try to find the sum of all "True" occurences in a dataframe我尝试在 dataframe 中找到所有“真实”出现的总和
df df
A B C D
1 True False True False
2 False False False True
3 True True False True
4 True False False True
Result showed by 8结果显示为 8
I tried我试过了
condition_total = df[df.values = True].counts()
I find solutions for columns but not for the whole dataframe我找到列的解决方案,但不是整个 dataframe
You can use df == something
to get a matrix of which values are equal to the data you're looking for.您可以使用
df == something
来获取其值等于您正在寻找的数据的矩阵。 You can then count the results per row using .sum()
and then sum up the column using .sum()
again.然后,您可以使用
.sum()
计算每行的结果,然后再次使用.sum()
对列求和。
The following code gives 9 using == False
and 7 using == True
.以下代码使用
== False
给出 9,使用== True
给出 7。
import pandas as pd
d = {"A": [True, False, True, True],
"B": [True, False, False, False],
"C": [True, False, False, False],
"D": [False, True, True, False]}
df = pd.DataFrame(data=d)
condition_total = (df == False).sum().sum()
print(condition_total)
The comparison with == True
is redundant, so it can just be df.sum().sum()
.与
== True
的比较是多余的,所以它可以只是df.sum().sum()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.