Deepak M
Deepak M

Reputation: 1224

Creating a new column in a data frame by mapping the values from a dictionary to an existing column

I have a dictionary like this:

dictionary = {100:[1, 2], 110:[3, 4], 
               120:[5, 6, 7], 130:[8, 9], 
               140:[10, 11, 12, 13], 
               150:[14, 15]}

I already have an existing column 'A' and would like to create a new column 'B' and map the values back to each key but display this in a data frame format. Here is the output I wish to receive:

 #Column A is the existing column. Column B is the new one to be created
    A     B 
    4     110
    8     130
    15    150
    7     120
    7     120
    4     110
    9     130
    1     100
    2     100

How can this be done? Help would be appreciated. Thanks in advance!

Upvotes: 2

Views: 258

Answers (1)

jpp
jpp

Reputation: 164843

Reverse your dictionary via a comprehension. Then use pd.Series.map with your new dictionary:

d = {100:[1, 2], 110:[3, 4], 120:[5, 6, 7], 130:[8, 9], 
     140:[10, 11, 12, 13], 150:[14, 15]}

d_rev = {w: k for k, v in d.items() for w in v}

df['B'] = df['A'].map(d_rev)

print(df)

    A    B
0   4  110
1   8  130
2  15  150
3   7  120
4   7  120
5   4  110
6   9  130
7   1  100
8   2  100

Upvotes: 4

Related Questions