Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace a pandas dataframe value using a dictionary as lookup

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My df should finally look like this:

text
1023
2213
1023
3346
2213
3346

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading