TheChymera
TheChymera

Reputation: 17934

Drop columns from pandas dataframe, regardless of whether ALL column names are present

I would like to use df.drop(drop_list, axis=1) to remove a number of columns from my data frame, however if an entry from drop_list is not present in df.columns.tolist(), the command fails, how can I prevent this from happening?

Upvotes: 2

Views: 585

Answers (2)

tanemaki
tanemaki

Reputation: 5069

df.drop(set(drop_list) & set(df.columns), axis=1)

Upvotes: 3

James Trimble
James Trimble

Reputation: 1866

I think this should work:

df.drop(set.intersection(set(drop_list), df.columns.tolist()), axis=1)

(Edited following EdChum's comment)

Upvotes: 1

Related Questions