40

How do I drop a row if any of the values in the row equal zero?

I would normally use df.dropna() for NaN values but not sure how to do it with "0" values.

azuric
  • 2,679
  • 7
  • 29
  • 44

4 Answers4

59

i think the easiest way is looking at rows where all values are not equal to 0:

df[(df != 0).all(1)]
acushner
  • 9,595
  • 1
  • 34
  • 34
  • 1
    I chose this answer because it is the most efficient in terms of coding but both answers appear to be accurate. – azuric Nov 20 '14 at 10:37
25

You could make a boolean frame and then use any:

>>> df = pd.DataFrame([[1,0,2],[1,2,3],[0,1,2],[4,5,6]])
>>> df
   0  1  2
0  1  0  2
1  1  2  3
2  0  1  2
3  4  5  6
>>> df == 0
       0      1      2
0  False   True  False
1  False  False  False
2   True  False  False
3  False  False  False
>>> df = df[~(df == 0).any(axis=1)]
>>> df
   0  1  2
1  1  2  3
3  4  5  6
DSM
  • 342,061
  • 65
  • 592
  • 494
23

Although it is late, someone else might find it helpful. I had similar issue. But the following worked best for me.

df =pd.read_csv(r'your file')
df =df[df['your column name'] !=0]

reference: Drop rows with all zeros in pandas data frame see @ikbel benabdessamad

non_linear
  • 413
  • 7
  • 15
  • Think this is the most legible if we just want to focus on one (or a group) of columns. – Fed May 26 '20 at 12:12
2

Assume a simple DataFrame as below:

df=pd.DataFrame([1,2,0,3,4,0,9])

Pick non-zero values which turns all zero values into nan and remove nan-values

df=df[df!=0].dropna()

df

Output:

    0
0   1.0
1   2.0
3   3.0
4   4.0
6   9.0
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
Arash
  • 21
  • 2