Ruzannah
Ruzannah

Reputation: 131

Counting Rows with Condition in Pandas

My pandas dataframe looks like following:

  a b c d e 
x 2 4 5 0 0
y 0 3 8 9 0
z 2 3 5 0 1

I want to count the rows where values != 0. I have tried this one but the output doesn't like what I expected :

df.sum(axis=1)
x 11
y 20
z 11

The output that I expected:

x 3
y 3
z 4

How can i do that?

Upvotes: 0

Views: 3609

Answers (1)

anky
anky

Reputation: 75080

Filter out the 0 by using .ne() which is equivalent of != and sum on axis=1, Use:

df.ne(0).sum(axis=1)
#alternatively (df!=0).sum(axis=1)

x    3
y    3
z    4

Upvotes: 1

Related Questions