3

I have a dataframe df1

df1 = pd.DataFrame({'c1': [1],
                    'c2': [2],
                    'c3': [3]})

I want to add columns to this dataframe using a dictionary dict

my_dict = {'c4': 4, 'c5': 5}

so I ultimately want df1 to become

df2 = pd.DataFrame({'c1': [1],
                    'c2': [2],
                    'c3': [3],
                    'c4': [4],
                    'c5': [5]})

What I have found on SO is only example where a dictionary is turned into a DataFrame along the rows, e.g. this thread - and not along columns as in the above question.

2 Answers 2

3

Use:

df = df1.join(pd.DataFrame([my_dict]))

Or:

df = pd.concat([df1, pd.DataFrame([my_dict])], axis=1)

print (df)
   c1  c2  c3  c4  c5
0   1   2   3   4   5
Sign up to request clarification or add additional context in comments.

Comments

3

Use pd.DataFrame.assign unpacking the dictionary into keyword arguments.

df1.assign(**my_dict)

   c1  c2  c3  c4  c5
0   1   2   3   4   5

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.