How do I delete columns that contain a zeros value in Pandas?

Viewed 114

I want to retain only non zero columns

df:

Names        Henry    Adam   Rachel  Jug   Jesscia
Robert         54      0        0     6       5
Dan            22      31       0     0       55

Expected output:

Names        Henry         Jesscia
Robert         54              5
Dan            22             55
df.loc[:, (df != 0).any(axis=0)]
did not remove the columns with only one zero value
3 Answers

Try:

df.loc[:,~df.eq(0).any()]

OR

as suggested by @sammywemmy

df.loc[:, df.ne(0).all()]

Other possible solutions:

df.mask(df.eq(0)).dropna(axis=1)
#OR
df.drop(df.columns[df.eq(0).any()],1)

output of above code:

    Names  Henry  Jesscia
0  Robert     54        5
1     Dan     22       55
df.loc[:, df.eq(0).sum().eq(0)]

or:

    df.where(df.ne(0)).dropna(1)
    Names   Henry   Jesscia
0   Robert  54      5
1   Dan     22      55

You can try with the following:

df.replace(0, np.nan).dropna(how='any', axis=1)
Related