我有一个包含金融机构交易的数据框。['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