John s
John s

Reputation: 174

How to "capture" drop multiple columns in pandas

I know one can drop multiple columns with

df.drop(columns=['col1', 'col2'],inplace=True)

I want to drop only if a column exists without throwing an error if it does not. For example, if only col2 exists, it should only drop col2. I know this can be done via a loop, or I can write my function, but I'm looking for a more native solution.

Upvotes: 1

Views: 74

Answers (1)

Mattravel
Mattravel

Reputation: 1607

You can ignore errors:

df.drop(columns=['col1', 'col2'], inplace=True, errors='ignore')

Upvotes: 3

Related Questions