how to add columns in pandas if its not present in dataframe

Viewed 453

I have following array of column names in python.

 col = ['code','ro','quantity','amount']

I get the processed dataframe from a function which may or may not have all the above columns. I want to add columns with default value as 0 if they are missing from the array.

e.g. I get following dataframe

df1

code      ro      quantity
123       342     34.56
123       445     54.56

My desired dataframe would be

code      ro      quantity  amount
123       342     34.56     0
123       445     54.56     0

How can I do it in pandas?

4 Answers

Use reindex over axis=1:

df.reindex(col,fill_value=0,axis=1)

   code   ro  quantity  amount
0   123  342     34.56       0
1   123  445     54.56       0

1). Short and simple solution if you know the basics of python and you do not have to memorise any new method.

col = ['code','ro','quantity','amount']

for var in col:
    if var not in df1.columns:
        df[var] = 0

I hope it may help you.

Code:-

col = ['code','ro','quantity','amount']
for i in col:
    if i not in df1.columns:
        df[i] = 0
for i in col :
   if i not in df:
      df[i] = 0 

Related