Skip to content
Advertisement

how to slice pandas dataframe columns with default values instead of error

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] })

enter image description here

I am trying to slice them so that I only have ['col1', 'col3', 'col4']

enter image description here

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?

enter image description here

Advertisement

Answer

Use:

df = df.reindex(['col1','col3', 'col4'], axis=1)

Or:

df = df.reindex(['col1','col3', 'col4'], axis=1, fill_value=0)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement