Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a dictionary to pandas series using lambda

I am trying to map a dictionary against a pandas series using lambda. Instead of mapping the values against the series 'Food', it's returning the whole dictionary against it. I know I need to amend the lambda function but don't know how.

data = pd.DataFrame({'food': ['bacon', 'pulled pork', 'bacon','Pastrami', 'corned beef', 'Bacon','pastrami', 'honey ham', 'nova lox'], 'ounces': [4, 3, 12, 6, 7.5, 8, 3, 5, 6]})

food_to_animal = {'bacon': 'pig',  'pulled pork': 'pig',  'pastrami': 'cow',  'corned beef': 'cow',  'honey ham': 'pig',  'nova lox': 'salmon'} 

data['food'].map(lambda x: food_to_animal)

​ OUTPUT: ​

0    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
1    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
2    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
3    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
4    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
5    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
6    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
7    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
8    {'bacon': 'pig', 'pulled pork': 'pig', 'pastra...
Name: food, dtype: object

EXPECTED OUTPUT:

0     pig
1     pig
2     pig
3     cow
4     cow
5     pig
6     cow
7     pig
8     salmon
like image 505
Hasham Beyg Avatar asked Jun 14 '26 04:06

Hasham Beyg


2 Answers

Please try make the df.food value lower case and map dictionary

 data['food'].str.lower().map(food_to_animal)

and to a column

data['x']= data['food'].str.lower().map(food_to_animal)

0       pig
1       pig
2       pig
3       cow
4       cow
5       pig
6       cow
7       pig
8    salmon
Name: food, dtype: object
like image 62
wwnde Avatar answered Jun 18 '26 01:06

wwnde


As a matter of fact, you do not need the lambda. Panda's replace knows how to work with dictionaries. Just make sure that the keys are in the right case:

data.food.str.lower().replace(food_to_animal)

P.S.: map + lambda work about 2x faster than replace or map + dictionary.

like image 27
DYZ Avatar answered Jun 17 '26 23:06

DYZ