metk
metk

Reputation: 99

Count occurence of a value (zero) in a column of a dataframe

I want to have the occurence of a value (in this case it's 0) of every column in my dataframe.

I tried this function that iterates a column col and count the number of 0. But I need to know the occurence of all the columns at once, meaning I won't need to use this function for every column.

def count_zero(df,col): 
    count = 0
    for ele in df[:,col]: 
        if (ele == 0): 
            count = count + 1
    return count 
print(count_zero(df,1))

Error message: TypeError: unhashable type: 'slice'

Upvotes: 2

Views: 1370

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13393

you can use .eq(0) to get a boolean df indicating where the value is 0, then use .sum() to get how many True values there are in each column.

example:

import pandas as pd

df = pd.DataFrame.from_dict(
    {"A": [x ** 2 if x % 2 else 0 for x in range(20)],
     "B": [x ** 3 if x % 3 else 0 for x in range(20)],
     "C": [x ** 5 if x % 5 else 0 for x in range(20)]})

print(df.eq(0).sum())

Output:

A    10
B     7
C     4

Upvotes: 1

Related Questions