[英]How to compare each row from one dataframe against all the rows from other dataframe and calculate distance measure?
[英]How can I compare each row from a dataframe against every row from another dataframe and see the difference between values?
我有兩個數據框:
df1
Code Number
0 ABC123 1
1 DEF456 2
2 GHI789 3
3 DEA456 4
df2
Code
0 ABD123
1 DEA458
2 GHI789
df1 就像一本字典,我可以通過檢查它們的代碼從中獲取每個項目的相應編號。 但是,有未注冊的代碼,如果我找到未注冊的代碼,我應該尋找看起來最像它們的代碼。 所以,結果應該是:
ABD123 = 1(因為它與 ABC123 有 1 個不同的字符)
DEA456 = 4(因為它有1個與DEA456不同的字符,2個來自DEF456,所以它選擇最接近的一個)
GHI789 = 3(因為它在 df1 有等價物)
我知道如何分別檢查每個代碼的差異並保存不同字符的“長度”,但我不知道如何應用此代碼,因為我不知道如何將 df2 中的每一行與所有行進行比較來自df1。 有辦法嗎?
不知道如何將 df2 中的每一行與 df1 中的所有行進行比較。
嵌套循環將起作用。 如果你有一個名為compare
的 function,它看起來像這樣......
for index2, row2 in df2.iterrows():
for index1, row1 in df1.iterrows():
difference = compare(row2,row1)
#do something with the difference.
使用 Pandas 或 Numpy 時,嵌套循環通常並不理想,但它們確實有效。 可能有更好的解決方案。
這也應該有效:
df['Code_e'] = df['Code'].str.extract(r'(\d+)').astype(int)
df2['Code_e'] = df2['Code'].str.extract(r'(\d+)').astype(int)
final_df = pd.merge_asof(df2,df.sort_values(by='Code_e'),on='Code_e',suffixes=('','_right')).drop(['Code_e','Code_right'],axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.