Skip to content

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')
Code language: Python (python)

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 3 1 4
Code language: Python (python)

See also  How to Fix 'no basic auth credentials' with Docker and AWS ECR
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x