Home > Mobile >  Pandas replace values if value isin dictionary of key and values as list
Pandas replace values if value isin dictionary of key and values as list

Time:01-19

I do realize this has already been addressed here (e.g., pandas: replace column value with keys and values in a dictionary of list values, Replace column values by dictionary keys if they are in dictionary values (list)). Nevertheless, I hope this question was different.

I want to replace values in the dataframe COl with key if the column value is present in the list values of the dictionary

Sample dataframe:

import pandas as pd

df = pd.DataFrame({"Col": ["Apple", "Appy", "aple","Banana", "Banaa", "Banananan", "Carrot", "Mango", "Pineapple"]})
remap_dict = {"Apple": ["Appy", "aple"],
              "Banana": ["Banaa", "Banananan"]}

pandas replace doesn't support dictionary with key value(list):

df["Col"].replace(remap_dict, regex=True)

Is there a way to replace values in the pandas dataframe with keys in the dictionary if the value is in the list??

Desired Output:

     Col
0   Apple
1   Apple
2   Apple
3   Banana
4   Banana
5   Banana
6   Carrot
7   Mango
8   Pineapple

CodePudding user response:

Use dict comprehension with flatten lists first:

d1 = {x: k for k, v in remap_dict.items() for x in v}
print (d1)
{'Appy': 'Apple', 'aple': 'Apple', 'Banaa': 'Banana', 'Banananan': 'Banana'}

And then use replace or mapping by map:

s = df["Col"].replace(d1)

s = df["Col"].map(d1).fillna(df['Col'])

print (s)
0        Apple
1        Apple
2        Apple
3       Banana
4       Banana
5       Banana
6       Carrot
7        Mango
8    Pineapple
Name: Col, dtype: object
  • Related