Drop row in pandas dataframe if any value in the row equals zero

Question:

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.

Asked By: azuric

||

Answers:

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

df = df[(df != 0).all(1)]
Answered By: acushner

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
Answered By: DSM

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
Answered By: Arash

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

Answered By: non_linear
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.