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

前端 未结 4 1122
粉色の甜心
粉色の甜心 2020-12-05 18:07

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.

相关标签:
4条回答
  • 2020-12-05 18:40

    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
    
    0 讨论(0)
  • 2020-12-05 18:45

    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

    0 讨论(0)
  • 2020-12-05 19:01

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

    df[(df != 0).all(1)]
    
    0 讨论(0)
  • 2020-12-05 19:03

    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
    
    0 讨论(0)
提交回复
热议问题