Neil
Neil

Reputation: 8247

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

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?

Upvotes: 3

Views: 2076

Answers (4)

user11779328
user11779328

Reputation:

Code:-

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

Upvotes: 2

Rahul charan
Rahul charan

Reputation: 837

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.

Upvotes: 1

tawab_shakeel
tawab_shakeel

Reputation: 3739

for i in col :
   if i not in df:
      df[i] = 0 

Upvotes: 0

anky
anky

Reputation: 75110

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

Upvotes: 5

Related Questions