1

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.