1

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.

John s
  • 164
  • 7
  • Don't use `inplace=True`, it will be deprecated => https://github.com/pandas-dev/pandas/issues/16529 – Corralien Feb 02 '23 at 03:59
  • @Corralien What is the alternative to inplace=true from a memory management perspective? – John s Feb 03 '23 at 05:29
  • If memory management is important for you, switch to pyarrow or downcast numeric types to avoid float64 / int64. Use category dtype to manage finite number of categories. These actions will reduce the memory footprint. – Corralien Feb 03 '23 at 07:11

1 Answers1

3

You can ignore errors:

df.drop(columns=['col1', 'col2'], inplace=True, errors='ignore')
Mattravel
  • 1,358
  • 1
  • 15