Find the most similar row using Python

大兔子大兔子 提交于 2021-02-07 10:11:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!