1

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

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Ahamed Moosa
  • 1,395
  • 7
  • 16
  • 30
  • 1
    Possible duplicate of [Drop row in pandas dataframe if any value in the row equals zero](https://stackoverflow.com/questions/27020312/drop-row-in-pandas-dataframe-if-any-value-in-the-row-equals-zero) – piroot Mar 17 '18 at 13:27

1 Answers1

2

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)] 
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252