首页 > 解决方案 > Pandas 使用字典替换值和值列表

问题描述

我有以下字典和系列。

product_type_dic = {'Facial Care':['Facial_cleanser', 'Beard_oil'], 'Eye Care':['Around-eye_cream', 'Eyeliner']}

s = pd.Series(['Facial_cleanser', 'Beard_oil', 'Around-eye_cream', 'Eyeliner'])

我的目标是使用 Series 获取字典的键值。所以结果将是

'Facial Care'
'Facial Care'
'Eye Care'
'Eye Care'

谢谢

标签: pandasdictionaryseries

解决方案


Series.map与逆product_type_dic字典一起使用:

product_type_dic = {
    "Facial Care": ["Facial_cleanser", "Beard_oil"],
    "Eye Care": ["Around-eye_cream", "Eyeliner"],
}


inv_product_type_dic = {vv: k for k, v in product_type_dic.items() for vv in v}
s = pd.Series(["Facial_cleanser", "Beard_oil", "Around-eye_cream", "Eyeliner"])

print(s.map(inv_product_type_dic))

印刷:

0    Facial Care
1    Facial Care
2       Eye Care
3       Eye Care
dtype: object

推荐阅读