F. Suyuti
F. Suyuti

Reputation: 327

Filter DataFrame if every row value in some Column is not zero

I have panda dataframe look like this:

'a', 'b', 'c' ,'d', ...., 'z'
-----------------------------
1  , 2  , 3   , 4 , ...., 6
1  , 0  , 3   , 4 , ...., 6
0  , 0  , 0   , 4 , ...., 6

If i want to filter using single column, for example a can't be zero, i can do something like this

`df = df[df.a != 0]`

But how if i need to filter using multiple column, for example a and b can't be zero?

The result that i want something like this:

'a', 'b', 'c' ,'d', ...., 'z'
-----------------------------
1  , 2  , 3   , 4 , ...., 6
1  , 0  , 3   , 4 , ...., 6

Upvotes: 0

Views: 3419

Answers (1)

jezrael
jezrael

Reputation: 862611

You can compare filtered columns with 0 with ne (same as !=) for new boolean DataFrame and then check if at least one Trues per row with any:

print (df[['a','b']])
   a  b
0  1  2
1  1  0
2  0  0

print (df[['a','b']].ne(0))
       a      b
0   True   True
1   True  False
2  False  False

print (df[['a','b']].ne(0).any(1))
0     True
1     True
2    False
dtype: bool

df = df[df[['a','b']].ne(0).any(1)]
print (df)
   a  b  c  d  z
0  1  2  3  4  6
1  1  0  3  4  6

Upvotes: 2

Related Questions