gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:21:30 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com