Drop rows with all zeros in pandas data frame

前端 未结 13 951
礼貌的吻别
礼貌的吻别 2020-11-27 11:57

I can use pandas dropna() functionality to remove rows with some or all columns set as NA\'s. Is there an equivalent function for drop

相关标签:
13条回答
  • 2020-11-27 12:25
    df = df [~( df [ ['kt'  'b'   'tt'  'mky' 'depth', ] ] == 0).all(axis=1) ]
    

    Try this command its perfectly working.

    0 讨论(0)
  • 2020-11-27 12:26
    import pandas as pd
    
    df = pd.DataFrame({'a' : [0,0,1], 'b' : [0,0,-1]})
    
    temp = df.abs().sum(axis=1) == 0      
    df = df.drop(temp)
    

    Result:

    >>> df
       a  b
    2  1 -1
    
    0 讨论(0)
  • 2020-11-27 12:26

    For me this code: df.loc[(df!=0).any(axis=0)] did not work. It returned the exact dataset.

    Instead, I used df.loc[:, (df!=0).any(axis=0)] and dropped all the columns with 0 values in the dataset

    The function .all() droped all the columns in which are any zero values in my dataset.

    0 讨论(0)
  • 2020-11-27 12:27

    Replace the zeros with nan and then drop the rows with all entries as nan. After that replace nan with zeros.

    import numpy as np
    df = df.replace(0, np.nan)
    df = df.dropna(how='all', axis=0)
    df = df.replace(np.nan, 0)
    
    0 讨论(0)
  • 2020-11-27 12:33

    I think this solution is the shortest :

    df= df[df['ColName'] != 0]
    
    0 讨论(0)
  • 2020-11-27 12:36

    One-liner. No transpose needed:

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

    And for those who like symmetry, this also works...

    df.loc[(df!=0).any(axis=1)]
    
    0 讨论(0)
提交回复
热议问题