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.

N08
  • 1,205
  • 9
  • 19

2 Answers2

4

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
piRSquared
  • 265,629
  • 48
  • 427
  • 571
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
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090