Ahamed Moosa
Ahamed Moosa

Reputation: 1445

How to delete the entire row if any of its value is 0 in pandas

In the below example I only want to retain the row 1 and 2 I want to delete all the rows which has 0 anywhere across the column:

kt  b   tt  mky depth
1   1   1   1   1   4
2   2   2   2   2   2
3   3   3   0   3   3
4   0   4   0   0   0
5   5   5   5   5   0

enter image description here

the output should read like below:

kt  b   tt  mky depth
1   1   1   1   1   4
2   2   2   2   2   2

enter image description here

I have tried:

df.loc[(df!=0).any(axis=1)] 

But it deletes the row only if all of its corresponding columns are 0

Upvotes: 1

Views: 424

Answers (1)

jezrael
jezrael

Reputation: 863411

You are really close, need DataFrame.all for check all Trues per row:

df = df.loc[(df!=0).all(axis=1)] 
print (df)
   kt  b  tt  mky  depth
1   1  1   1    1      4
2   2  2   2    2      2

Details:

print (df!=0)
      kt     b     tt    mky  depth
1   True  True   True   True   True
2   True  True   True   True   True
3   True  True  False   True   True
4  False  True  False  False  False
5   True  True   True   True  False

print ((df!=0).all(axis=1))
1     True
2     True
3    False
4    False
5    False
dtype: bool

Alternative solution with any for check at least one True for row with changed mask df == 0 and inversing by ~:

df = df.loc[~(df==0).any(axis=1)] 

Upvotes: 2

Related Questions