Home > Software design >  Drop all the columns of pandas DataFrame whose names match with the names given in a list
Drop all the columns of pandas DataFrame whose names match with the names given in a list

Time:01-02

I am dealing with pandas DataFrame (df) within a for loop that may have different columns. For example, for the first loop, df may have columns: "A", "B", "C", "D", and "E". For the second loop, df may have columns: "B", "C", "E", "F", "G", and "H". I want to drop certain columns e.g., "A" , "F", and "G" from df. If I use the line below within the for loop, It will result an error: "['F' 'G'] not found in axis."

df = df.drop(['A', 'F', 'G'], axis=1)

Similarly, for the second loop, It will result an error: "['A'] not found in axis." How to solve this problem?

CodePudding user response:

Try with pass errors = 'ignore'

out = df.drop(["A","F","G"], errors = 'ignore', axis = 1)

CodePudding user response:

Filter the list of columns to only include those that are actually present in the DataFrame, eg:

df = df.drop(df.columns.intersection(['A', 'F', 'G']), axis=1)
  • Related