我有一个数据框,其中包含来自金融机构的交易。列['vendor_full']中的一列是供应商,但其中可能包含商店编号,实际位置等。因此,很难根据供应商的实际情况来进行总结。
我创建了一个字典,其中的键是可能出现在数据框中(或至少一部分列字符串)的供应商名称,值是我希望写入的供应商名称。新列['vendor_short']。
基于this问题和@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
答案 0 :(得分:1)
我们会根据您的字典制作数据框。然后,我们提取您的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