[英]Match Strings of 2 dataframe columns in Python
我有兩個數據框:
DF1:
原始df有1000+名稱
Id Name
1 Paper
2 Paper Bag
3 Scissors
4 Mat
5 Cat
6 Good Cat
第二個Df:
原始df有1000+ Item_Name
Item_ID Item_Name
1 Paper Bag
2 wallpaper
3 paper
4 cat cage
5 good cat
預期產出:
Id Name Item_ID
1 Paper 1,2,3
2 Paper Bag 1,2,3
3 Scissors NA
4 Mat NA
5 Cat 4,5
6 Good Cat 4,5
我的代碼:
def matcher(x):
res = df2.loc[df2['Item_Name'].str.contains(x, regex=False, case=False), 'Item_ID']
return ','.join(res.astype(str))
df1['Item_ID'] = df1['Name'].apply(matcher)
當前的挑戰
當name具有Paper並且Item_Name具有Paper Bag時str.contains
工作但是它不能以其他方式工作。 所以,我的例子是為1,3,4,5行工作df1
而不是2行和6。因此,它不會 與DF2的3行映射DF1第2行
問
所以,如果你可以幫我修改代碼,那么它也可以幫助匹配其他方法
您可以修改自定義matcher
功能並使用apply()
:
def matcher(query):
matches = [i['Item_ID'] for i in df2[['Item_ID','Name']].to_dict('records') if any(q in i['Name'].lower() for q in query.lower().split())]
if matches:
return ','.join(map(str, matches))
else:
return 'NA'
df1['Item_ID'] = df1['Name'].apply(matcher)
返回:
Id Name Item_ID
0 1 Paper 1,2,3
1 2 Paper Bag 1,2,3
2 3 Scissors NA
3 4 Mat NA
4 5 Cat 4,5
5 6 Good Cat 4,5
說明:
我們使用apply()
將自定義matcher()
函數應用於df1['Name']
列的每個行值。 在我們的matcher()
函數中,我們將df2
轉換為字典,其中Item_ID
為鍵, Name
為值。 然后我們可以檢查我們當前的行值query
是否存在於來自df1
any()
的Name
值中(通過lower()
轉換為小寫),如果是,那么我們可以將Item_ID
添加到要返回的列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.