Replace a pandas dataframe value using a dictionary as lookup

Question:

I have a Pandas df column ‘text’ like so:

text
Aztecs
Apple
Mayans
Christopher
Banana
Martin

I have a dictionary with integer as key and list as value. For example,
d = {1023: ['Aztecs', 'Mayans'], 2213: ['Apple','Banana'], 3346: ['Christopher', 'Martin']}

I want to replace each value in df[‘text’] to have the corresponding key from the dictionary. I am confused on how to solve this!

My df should finally look like this:

text
1023
2213
1023
3346
2213
3346
Asked By: LVA

||

Answers:

Create an inverse dictionary and use .map:

inv_d = {vv: k for k, v in d.items() for vv in v}

df["text 2"] = df["text"].map(inv_d)
print(df)

Prints:

          text  text 2
0       Aztecs    1023
1        Apple    2213
2       Mayans    1023
3  Christopher    3346
4       Banana    2213
5       Martin    3346
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.