Add lists inside dictionary to DataFrame as new columns
Let's say I have the following pandas DataFrame:
df = pd.DataFrame({'x': [0, 1, 2], 'y': [3, 4, 5], 'z': [6, 7, 8]})
x y z
0 0 3 6
1 1 4 7
2 2 5 8
And the following dictionary:
d = {'a': [10, 10, 10], 'b': [100, 100, 100]}
What's the best way to add a dictionary to the DataFrame to get the following:
x y z a b
0 0 3 6 10 100
1 1 4 7 10 100
2 2 5 8 10 100
This is what I have come up with so far, but I feel like there must be a better way:
df_bigger = pd.concat([df, pd.DataFrame(d)], axis=1)
+3
source to share
4 answers
One way to do it:
dataframe_dict = pd.DataFrame.to_dict(orient='dict')
d = {'a': [10, 10, 10], 'b': [100, 100, 100]}
new_dict = dict(dataframe_dict.items() + d.items())
By the way, I have never used DataFrames, but here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html , it says you can convert dataframe to dict, so I just converted it and created a new dict with other elements included.
+1
source to share