Reputation: 23
In a pandas dataframe, I need to find columns that contain a zero in any row, and drop that whole column.
For example, if my dataframe looks like this:
A B C D E F G H
0 1 0 1 0 1 1 1 1
1 0 1 1 1 1 0 1 1
I need to drop columns A, B, D, and F. I know how to drop the columns, but identifying the ones with zeros programmatically is eluding me.
Upvotes: 2
Views: 2127
Reputation: 88236
You can use .loc
to slice the dataframe and perform boolean indexation on the columns, checking which have any
0
in them:
df.loc[:,~(df==0).any()]
C E G H
0 1 1 1 1
1 1 1 1 1
Or equivalently you can do:
df.loc[:,(df!=0).all()]
Upvotes: 3
Reputation: 8981
Try this:
Code:
import pandas as pd
df = pd.DataFrame({'A': [1, 1, 1], 'B': [1, 0, 1]})
for col in df.columns:
if 0 in df[col].tolist():
df = df.drop(columns=col)
df
Upvotes: 0