Home > Enterprise >  Drop column of pd dataframe if one specific entry is 0
Drop column of pd dataframe if one specific entry is 0

Time:10-06

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

CodePudding user response:

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)

CodePudding user response:

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)
  • Related