使用Lambda将字典映射到熊猫系列

时间:2020-06-05 23:09:53

标签: python-3.x pandas lambda mapping series

我正在尝试使用lambda将字典与熊猫系列相对应。与其根据“食物”系列映射值,不如将其返回整个字典。我知道我需要修改lambda函数,但不知道如何。

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)

输出:

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

期望的输出:

0     pig
1     pig
2     pig
3     cow
4     cow
5     pig
6     cow
7     pig
8     salmon

3 个答案:

答案 0 :(得分:1)

请尝试制作df.foodlower casemap字典

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

并进入列

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

答案 1 :(得分:1)

这是将数字映射到日期名称的确切解决方案。 'timeStamp' 是包含日期的列,例如 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']

答案 2 :(得分:0)

事实上,您不需要lambda。熊猫的replace知道如何使用字典。只需确保密钥在正确的情况下即可:

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

P.S .: map + lambda的运行速度比replacemap +词典快2倍。