Mapping a dictionary to pandas series using lambda

Viewed 2273

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
3 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

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.

That's the exact solution to map the numbers into day name. 'timeStamp' is the column that contain the date like 2015-12-10 17:40:00

    df['Day of Week']=df['timeStamp'].apply(lambda time: time.dayofweek)
    dmap = {0:'Mon',1:'Tue',2:'Wed',3:'Thu',4:'Fri',5:'Sat',6:'Sun'}
    
    df['Day of Week'] = df['Day of Week'].map(dmap)
    df['Day of Week']
Related