I try to find the sum of all "True" occurences in a dataframe
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
I tried
condition_total = df[df.values = True].counts()
I find solutions for columns but not for the whole dataframe
You can use df == something
to get a matrix of which values are equal to the data you're looking for. You can then count the results per row using .sum()
and then sum up the column using .sum()
again.
The following code gives 9 using == False
and 7 using == True
.
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()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.