[英]Search for dictionary key within DataFrame column and return dictionary value in a new column
我有一个数据框,其中包含来自金融机构的交易。 列['vendor_full']之一是卖方,但其中可能包含商店编号,实际位置等,因此很难根据卖方的实际身份进行汇总。
我创建了一个字典,其中的键是供应商名称,因为它可能会出现在数据框中(或至少一部分列字符串),而值是供应商名称,就像我希望将其写入新列一样[ 'vendor_short']。
基于这个问题和@Vaishali的回答,我很接近解决方案,但是不同之处在于,上面发布问题的用户希望将字典值用作搜索词和返回值。 我想搜索键并返回值。
import pandas as pd
data = {'amount': [100, 150, 5, 89, 55, 14], 'vendor_full': ['store_name 1234', 'online_store xx55', 'st_name 9876', 'grocery_store', 'online_shop', 'clothing_store xx']}
cols = ['amount', 'vendor_full']
df = pd.DataFrame(data,columns = cols)
vendor_dict = {'store_name': 'store_name', 'online_store': 'online_store', 'st_name': 'store_name', 'grocery_store': 'grocery_store', 'online_shop': 'online_store', 'clothing_store': 'clothing_store'}
pat = r'({})'.format('|'.join(vendor_dict.values()))
cond = df['vendor_full'].str.contains('|'.join(vendor_dict.keys()))
df.loc[cond, 'vendor_short'] = df['vendor_full'].str.extract((pat), expand=False)
上面的代码似乎适用于第一次出现的供应商,但是对于其余的出现,我得到的是NaN。
实际:
amount vendor_full vendor_short
0 100 store_name 1234 store_name
1 150 online_store xx55 online_store
2 5 st_name 9876 NaN
3 89 grocery_store grocery_store
4 55 online_shop NaN
5 14 clothing_store xx clothing_store
预期/期望:
amount vendor_full vendor_short
0 100 store_name 1234 store_name
1 150 online_store xx55 online_store
2 5 st_name 9876 store_name
3 89 grocery_store grocery_store
4 55 online_shop online_store
5 14 clothing_store xx clothing_store
首先,我们根据您的要求制作数据框。 然后,我们提取您df
的名称,以便我们可以合并这些名称并获得vendor_short
:
df2 = pd.DataFrame({'vendor_full':list(vendor_dict.keys()),
'vendor_short':list(vendor_dict.values())})
s = df['vendor_full'].str.extract("({})".format('|'.join(df2['vendor_full'])))
df['vendor_short'] = s.merge(df2, left_on=0, right_on='vendor_full')['vendor_short']
amount vendor_full vendor_short
0 100 store_name 1234 store_name
1 150 online_store xx55 online_store
2 5 st_name 9876 store_name
3 89 grocery_store grocery_store
4 55 online_shop online_store
5 14 clothing_store xx clothing_store
使用.map
:
s = df['vendor_full'].str.extract("({})".format('|'.join(vendor_dict.keys())))
df['vendor_short'] = s[0].map(vendor_dict)
amount vendor_full vendor_short
0 100 store_name 1234 store_name
1 150 online_store xx55 online_store
2 5 st_name 9876 store_name
3 89 grocery_store grocery_store
4 55 online_shop online_store
5 14 clothing_store xx clothing_store
由cs95在评论中提供
使用正则表达式从vendor_full
列中提取名称,然后使用.map
将它们映射到字典:
df['vendor_short'] = df['vendor_full'].str.extract('([a-zA-Z_]+)', expand=False).map(vendor_dict)
amount vendor_full vendor_short
0 100 store_name 1234 store_name
1 150 online_store xx55 online_store
2 5 st_name 9876 store_name
3 89 grocery_store grocery_store
4 55 online_shop online_store
5 14 clothing_store xx clothing_store
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.