【问题标题】:Pandas replace values using dictionary with a list of valuesPandas 使用字典替换值和值列表
【发布时间】:2021-09-22 23:04:01
【问题描述】:

我有以下字典和系列。

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'

谢谢

【问题讨论】:

    标签: pandas dictionary series


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 2020-07-11
      • 2019-04-07
      • 2019-12-07
      • 1970-01-01
      • 2018-02-08
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多