freshman_2021
freshman_2021

Reputation: 371

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

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

Upvotes: 2

Views: 492

Answers (3)

Allen Qin
Allen Qin

Reputation: 19957

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

Upvotes: 0

Anurag Dabas
Anurag Dabas

Reputation: 24322

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

Upvotes: 5

GabrielP
GabrielP

Reputation: 782

You can try with the following:

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

Upvotes: 0

Related Questions