How to Drop Columns in Pandas Only if Exists


If you have a Pandas DataFrame, and want to only drop columns if they exist, then you can do the following:

Add parameter errors to DataFrame.drop:

errors : {‘ignore', ‘raise'}, default ‘raise'

If ‘ignore', suppress error and only existing labels are dropped.

df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore')

An example of how to Ignore Errors with .drop()

df = pd.DataFrame({'row_num':[1,2], 'w':[3,4]})
df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore')
print (df)
   w
0  3
1  4