Create Dataframe column that uses a dictionary to map the corresponding key,value in a dataframe

Viewed 57

Looking to create a dataframe column that will take data from a dictionary and search DF for the value. Example below:

DF1:

ColA    ColB    ColC    ColD
Dog      4.5     1.3     6.4
Cat      154      89      2
Frog     8        x       9

Dictionary = {'Dog':'ColC', 'Cat':'ColB', 'Frog':'ColD'}

Desired Dataframe: 'NewCol' column uses the dictionary to find the proper value

ColA    ColB    ColC    ColD    NewCol
Dog      4.5     1.3     6.4      1.3
Cat      154      89      2       154 
Frog     8        x       9        9

Thanks for the help!!

1 Answers

You can use lookup:

df['new_col'] = df.set_index('ColA').lookup(Dictionary.keys(), Dictionary.values())

Output:

   ColA   ColB ColC  ColD new_col
0   Dog    4.5  1.3   6.4     1.3
1   Cat  154.0   89   2.0     154
2  Frog    8.0    x   9.0       9
Related