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)
Use assign
with dictionary unpacking
df.assign(**d)
x y z a b
0 0 3 6 10 100
1 1 4 7 10 100
2 2 5 8 10 100
Note that if assign
, if the length of the lists is consistent with the dataframe, then the indexes take care of that.
You can use join (). And like @piRsquared mentioned in the comment, pass the index like this.
df = df.join(pd.DataFrame(d, index = df.index))
x y z a b
0 0 3 6 10 100
1 1 4 7 10 100
2 2 5 8 10 100
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.
#merge existing data with the new dict and re-construct a DF.
pd.DataFrame(dict(df.to_dict(orient='list'),**d))
Out[186]:
a b x y z
0 10 100 0 3 6
1 10 100 1 4 7
2 10 100 2 5 8