I have a following set of dataframes
df1 = pd.DataFrame({'col1':[1234, 12345], 'col2':[123, 345], 'col3':[1000,1000] }) df2 = pd.DataFrame({'col1':[1234, 12345], 'col2':[123, 345], 'col3':[1000,1000], 'col4':[1000,1000] })
I am trying to slice them so that I only have ['col1', 'col3', 'col4']
While I’m able to achieve that using slicing df[['col1','col3', 'col4']]
, in the case that col4
doesn’t exist , it gives an error. Is it possible to put a default value e.g. nil
or 0
in case col4 doesn’t exist so that I get the following when I run slicing with df1?
Advertisement
Answer
Use:
df = df.reindex(['col1','col3', 'col4'], axis=1)
Or:
df = df.reindex(['col1','col3', 'col4'], axis=1, fill_value=0)