Home > OS >  Drop Column in Pandas Dataframe based on Row Conidtion
Drop Column in Pandas Dataframe based on Row Conidtion

Time:06-22

I have the following pandas dataframe and I would like to drop any column that has 0-Flat in the "Trade" row. How would I go about doing that?

enter image description here

CodePudding user response:

This should do the job

headers_to_drop=[header for header in df.columns if (df[header]=="0-Flat").any()]
df=df.drop(headers_to_drop,axis=1)

The code first loops over all the columns and checks if there is any columns with the string and drops the selected columns.

CodePudding user response:

You can use replace beside dropna() to look through the whole df and remove all columns that contained the 0-Flat string

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'Column1' : ['1', '2', '3', '0-Flat'],
    'Column2' : ['1', '2', '3', '4'],
    'Column3' : ['1', '2', '0-Flat', '0']
})

df.replace('0-Flat', np.nan).dropna(axis = 1)
  • Related