How one can Drop Columns in Pandas Solely If Exists

In case you have a Pandas DataFrame, and wish to solely drop columns in the event that they exist, then you are able to do the next:

Add parameter errors to DataFrame.drop:

errors : {‘ignore’, ‘elevate’}, default ‘elevate’

If ‘ignore’, suppress error and solely present labels are dropped.

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

An instance of the way 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