Karush Kuhn Tucker
Karush Kuhn Tucker

Reputation: 9

Drop column of pd dataframe if one specific entry is 0

I'm trying to drop columns from a df in which one spec. entry is 0. So in the pic I wont to drop Loan F to Loan P cause the entries in row zero is 0. Can anyone help here? Thx!

enter image description here

Upvotes: 0

Views: 583

Answers (2)

Redox
Redox

Reputation: 10017

To do this, iterate through each column, see if the first row (assume that is where you are looking for the zero) value is equal to 0 and delete that column if true.

for col in df.columns:
    if df[col].iloc[0] == 0:
        df.drop(col, axis=1, inplace=True)

Upvotes: 0

C.Nivs
C.Nivs

Reputation: 13106

To check if a column contains a particular value, you'll want to use df.any():

(df['Loan F'] == 0).any()
True

Next, just loop this condition through all of your columns:

columns = [c for c in df.columns if (df[c] == 0).any()]

And then drop those

df = df.drop(columns)

Upvotes: 1

Related Questions