Reputation: 8247
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
Reputation:
Code:-
col = ['code','ro','quantity','amount']
for i in col:
if i not in df1.columns:
df[i] = 0
Upvotes: 2
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