Reputation: 1227
I have the following line of code that is used to drop some columns in a DataFrame. It may happen that some of these columns do not exist in the DataFrame.
df =
col1 col2 col3
asa 132 4534
dfd 24 4252
cols = ["col1", "colB"]
df.drop(cols, inplace=True, axis=1)
How can I skip the columns that do not exist?
Expected output:
df =
col2 col3
132 4534
24 4252
Upvotes: 0
Views: 54
Reputation: 301
import pandas as pd
col1 = ['asa', 'dfd']
col2 = [132, 24]
col3 = [4523, 4252]
cols = {'col1':col1,'col2':col2, 'col3':col3}
df = pd.DataFrame(cols)
drop_cols = ['col1', 'colB']
for col in drop_cols:
if col in df.columns.values:
df.drop(col, inplace = True, axis = 1)
df
returns what you're looking for.
col2 col3
0 132 4523
1 24 4252
Upvotes: 0
Reputation: 323366
Check with errors='ignore'
cols = ["col1", "colB"]
df.drop(cols, axis=1, errors='ignore', inplace=True)
df
Out[167]:
col2 col3
0 132 4534
1 24 4252
Upvotes: 4