【问题标题】:Create dataframe column by mapping against a dictionary that contains a subset of string value in another column. as its key通过映射包含另一列中字符串值子集的字典来创建数据框列。作为它的关键
【发布时间】:2019-02-11 02:14:25
【问题描述】:

我有一个字典商店,其中包含作为键的出口名称和作为其值的出口类型

stores = {'McDonalds':'Fast food','African and Eastern Beverage':'Alcohol','Baskin Robbins': 'ice Cream'}

我有一个 pandas 数据框,其中包含商店名称以及分支位置(在 Merchant 列中),其中一些具有 MerchantType 的 NaN 值

我需要填充具有 NaN 值的行的 MerchantType 列,并使用商店字典匹配商家类型,记住商店字典不包含位置(阿布扎比、迪拜、华盛顿等)在键中。

print (df)    
                                     Merchant MerchantType
index                                                     
0                         McDonalds Abu Dhabi          NaN
1                               Dunkin Donuts       Sweets
2          African and Eastern Beverage Dubai          NaN
3                                 Burger King    Fast Food
4      African and Eastern Beverage Abu Dhabi          NaN
5                                 Burger King    Fast Food
6                   Baskin Robbins Washington          NaN

完成这项工作最有效的方法是什么?

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    在字典中循环并仅设置str.contains 的匹配值和MerchantType 列中的缺失值:

    mask = df['MerchantType'].isnull()
    for k, v in stores.items():
        df.loc[df['Merchant'].str.contains(k, regex=False) & mask, 'MerchantType'] = v
    
    print (df)
                                         Merchant MerchantType
    index                                                     
    0                         McDonalds Abu Dhabi    Fast food
    1                               Dunkin Donuts       Sweets
    2          African and Eastern Beverage Dubai      Alcohol
    3                                 Burger King    Fast Food
    4      African and Eastern Beverage Abu Dhabi      Alcohol
    5                                 Burger King    Fast Food
    6                   Baskin Robbins Washington    ice Cream
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2021-01-18
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2021-01-26
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多