Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding columns to a dataframe using a dict

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.

like image 348
N08 Avatar asked Jun 22 '26 08:06

N08


1 Answers

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
like image 174
jezrael Avatar answered Jun 23 '26 22:06

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!