Rolf12
Rolf12

Reputation: 771

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

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

Upvotes: 2

Views: 830

Answers (1)

Thomas Weller
Thomas Weller

Reputation: 59259

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

Upvotes: 1

Related Questions