有一个有价值的数据框ABC
id | price | type
0 easdca | Rs.1,599.00 was trasn by you | unknown
1 vbbngy | txn of INR 191.00 using | unknown
2 awerfa | Rs.190.78 credits was used by you | unknown
3 zxcmo5 | DLR.2000 credits was used by you | unknown
和其他有价值的XYZ
price | type
0 190.78 | food
1 191.00 | movie
2 2,000 | football
3 1,599.00 | basketball
如何使用ABC映射XYZ,以便ABC中的类型使用XYZ价格中的值(数字)更新xyz中的类型。
输出我需要
id | price | type
0 easdca | Rs.1,599.00 was trasn by you | basketball
1 vbbngy | txn of INR 191.00 using | movie
2 awerfa | Rs.190.78 credits was used by you | food
3 zxcmo5 | DLR.2,000 credits was used by you| football
用过这个
d = dict(zip(XYZ['PRICE'],XYZ['TYPE']))
pat = (r'({})'.format('|'.join(d.keys())))
ABC['TYPE']=ABC['PRICE'].str.extract(pat,expand=False).map(d)
但是像190.78和191.00这样的价值观正在变得不匹配。例如,当处理大量数据时,190.78应该与食物值匹配,例如190.77与食物不匹配,其中它具有分配给它的其他值。 198.78也与其他一些与食物相匹配的产品不匹配
DF
id price type
0 easdca Rs.1,599.00 was trasn by you unknown
1 vbbngy txn of INR 191.00 using unknown
2 awerfa Rs.190.78 credits was used by you unknown
3 zxcmo5 DLR.2000 credits was used by you unknown
DF2
price type
0 190.78 food
1 191.00 movie
2 2,000 football
3 1,599.00 basketball
使用re
df['price_'] = df['price'].apply(lambda x: re.findall(r'(?<=[\.\s])[\d\.]+',x.replace(',',''))[0])
df2.columns = ['price_','type']
df2['price_'] = df2['price_'].str.repalce(',','')
将类型更改为float
df2['price_'] = df2['price_'].astype(float)
df['price_'] = df['price_'] .astype(float)
使用pd.merge
df = df.merge(df2, on='price_')
df.drop('type_x', axis=1)
产量
id price price_ type_y
0 easdca Rs.1,599.00 was trasn by you 1599.00 basketball
1 vbbngy txn of INR 191.00 using 191.00 movie
2 awerfa Rs.190.78 credits was used by you 190.78 food
3 zxcmo5 DLR.2000 credits was used by you 2000 football
您可以执行以下操作:
'''
First we make a artificial key column to be able to merge
We basically just substract the floating numbers from the string
And convert it to type float
'''
df1['price_key'] = df1['price'].str.replace(',', '').str.extract('(\d+\.\d+)').astype(float)
# After that we do a merge on price and price_key and drop the columns which we dont need
df_final = pd.merge(df1, df2, left_on='price_key', right_on='price', suffixes=['', '_2'])
df_final = df_final.drop(['type', 'price_key', 'price_2'], axis='columns')
产量
id price type_2
0 easdca Rs.1,599.00 was trasn by you basketball
1 vbbngy txn of INR 191.00 using movie
2 awerfa Rs.190.78 credits was used by you food
3 zxcmo5 DLR.2000.78 credits was used by you football
我假设你在xyz
表中输了一个错字,第三个价格应该是2000.78
而不是2000
。