Home > OS >  Replace a pandas dataframe value using a dictionary as lookup
Replace a pandas dataframe value using a dictionary as lookup

Time:10-12

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

CodePudding user response:

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
  • Related