python - 通过映射到包含另一列中字符串值子集的字典来创建数据帧列。作为其关键

标签 python pandas dataframe dictionary

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

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

完成此任务最有效的方法是什么?

最佳答案

循环字典并仅设置 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

关于python - 通过映射到包含另一列中字符串值子集的字典来创建数据帧列。作为其关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619316/

相关文章:

python-3.x - 如何在Python中将具有相同值的两行合并为单行?

python - 在 Pandas 数据框中检索 NaN 值的索引

r - 如何提取数据框列表中的列名称?

python - 为什么编译的 python 正则表达式更慢?

python - 如何使用 bool 型方形对称 numpy 数组中的真值存储存储索引对?

python - 如何选择与特定行匹配的行

python - Power BI Rest API 请求未按预期授权

python - 从 Pandas 数据框的两列创建矩形热图

python - 用 NaN 替换整数会导致整个列变成 float 据类型

python - Groupby pandas 按特定公式