ubuntu_noob
ubuntu_noob

Reputation: 2365

Count number of columns having zeros

My data frame-

df = pd.DataFrame([[1,2,0],[4,5,0],[7,8,0]])

I want to calculate the number of columns which have all the rows as zero in it. In the above case, the 3rd column has all zeros so the output would be 1

Upvotes: 2

Views: 485

Answers (3)

gilf0yle
gilf0yle

Reputation: 1102

this would easy and compact solution try it

    df = pd.DataFrame([[0,2,0],[0,5,0],[0,8,0]])
    df=(df.sum())
    answer=(df==0).sum()

Upvotes: 0

Equinox
Equinox

Reputation: 6748

Another alternative.

df.astype(bool).sum(axis=0).isin([0]).sum()

Upvotes: 0

anky
anky

Reputation: 75080

You can use df.sum and then series.sum:

df.sum().eq(0).sum()
#1

Upvotes: 1

Related Questions