问题
I have two data frames (df1 and df2). In the df1 I store one row with a set of values and I want to find the most similar row in the df2.
import pandas as pd
import numpy as np
# Df1 has only one row and four columns.
df1 = pd.DataFrame(np.array([[30, 60, 70, 40]]), columns=['A', 'B', 'C','D'])
# Df2 has 50 rows and four columns
df2 = pd.DataFrame(np.random.randint(0,100,size=(50, 4)), columns=list('ABCD'))
Question: Based on the df1 what is the most similar row in df2?
回答1:
If you want the min distance , we can using scipy.spatial.distance.cdist
import scipy
ary = scipy.spatial.distance.cdist(df2, df1, metric='euclidean')
df2[ary==ary.min()]
Out[894]:
A B C D
14 16 66 83 13
回答2:
Subtract df2 with df1 and calculate the norm of each row. Find the smallest norm and solve the problem.
diff_df = df2 - df1.values
# or diff_df = df2 - df1.iloc[0, :]
norm_df = diff.apply(np.linalg.norm, axis=1)
df2.loc[norm_df.idxmin()]
It is readable and fast.
来源:https://stackoverflow.com/questions/55779647/find-the-most-similar-row-using-python