hernanavella
hernanavella

Reputation: 5552

In Python, how can I transform a dictionary into a df column, where the keys match the df.index values?

I have a dataframe and a dictionary, the keys of the dict are the same as the index value of the dataframe, like these:

A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
                 columns=['A', 'B', 'C'], index=["1a", "2a", "3a", "4a", "5a"])

B = {'1a': 0.5, '2a': 0.75, '3a': 0.625, '4a': 0.55, '5a': 1}

How can I convert the values of the dictionary into values of a column in the dataframe, matching their respective key - index value. So the output would be like this:

    A  B  C  D
1a  1  5  2  0.5
2a  2  4  4  0.75
3a  3  3  1  0.625
4a  4  2  2  0.55
5a  5  1  4  1

The new column 'D' has all the values from the dictionary 'B' and each index value in the dataframe matches it correspondent key value in the dict.

Thanks

Upvotes: 4

Views: 450

Answers (1)

ely
ely

Reputation: 77424

You can wrap the dict with pandas.Series and then simply create it as a column:

In [633]: A['D'] = pd.Series(B)

In [634]: A
Out[634]: 
    A  B  C      D
1a  1  5  2  0.500
2a  2  4  4  0.750
3a  3  3  1  0.625
4a  4  2  2  0.550
5a  5  1  4  1.000

Upvotes: 4

Related Questions