Count True/False occurences across dataframe (columns & rows)

Viewed 200

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

1 Answers

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().

Related