Drop rows with all zeros in pandas data frame

前端 未结 13 1218
礼貌的吻别
礼貌的吻别 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:39

    You can use a quick lambda function to check if all the values in a given row are 0. Then you can use the result of applying that lambda as a way to choose only the rows that match or don't match that condition:

    import pandas as pd
    import numpy as np
    
    np.random.seed(0)
    
    df = pd.DataFrame(np.random.randn(5,3), 
                      index=['one', 'two', 'three', 'four', 'five'],
                      columns=list('abc'))
    
    df.loc[['one', 'three']] = 0
    
    print df
    print df.loc[~df.apply(lambda row: (row==0).all(), axis=1)]
    

    Yields:

                  a         b         c
    one    0.000000  0.000000  0.000000
    two    2.240893  1.867558 -0.977278
    three  0.000000  0.000000  0.000000
    four   0.410599  0.144044  1.454274
    five   0.761038  0.121675  0.443863
    
    [5 rows x 3 columns]
                 a         b         c
    two   2.240893  1.867558 -0.977278
    four  0.410599  0.144044  1.454274
    five  0.761038  0.121675  0.443863
    
    [3 rows x 3 columns]
    

提交回复
热议问题