anat
anat

Reputation: 143

Adding keys from dict to columns headers in an existing Pandas dataframe

I have a dataframe ('DF1') and I have a dict ('dictdf'). I want to add columns headers based on the dict, those columns needs to be empty.

DF1:

ID  age

12   33
23   55
67   12

result:

ID  age  height  eye_color  ....  

12   33    NA      NA       ....
23   55    NA      NA       ....
67   12    NA      NA       ....

This is what I tried:

colNames = DF1.columns
for key in dictdf.keys():
    colNames.append(key)

newDF = pd.DataFrame(DF1,columns=colNames)

Error:

TypeError: all inputs must be Index

Any idea on a simple solution? I don't want to start transforming from dict to DF or the other way around.

Upvotes: 1

Views: 1667

Answers (2)

jezrael
jezrael

Reputation: 862771

Use append for all cols with reindex:

d = {'height': 120, 'eye_color': 'brown'}

df = df.reindex(columns=df.columns.append(pd.Index(d)))
print (df)
   ID  age  height  eye_color
0  12   33     NaN        NaN
1  23   55     NaN        NaN
2  67   12     NaN        NaN

Upvotes: 1

jpp
jpp

Reputation: 164693

You can use pd.DataFrame.join with an empty dataframe with defined columns. As a single operation, this will be more efficient than manual appending columns in a loop.

d = {'height': 120, 'eye_color': 'brown'}

df = df.join(pd.DataFrame(columns=d))

print(df)

   ID  age height eye_color
0  12   33    NaN       NaN
1  23   55    NaN       NaN
2  67   12    NaN       NaN

Upvotes: 1

Related Questions