Search code examples
pythonpandasdrop

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.


Solution

  • You can ignore errors:

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