使用Python查找最相似的行 [英] Find the most similar row using Python
本文介绍了使用Python查找最相似的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数据帧(df1和df2).在df1中,我将一行存储一组值,并希望在df2中找到最相似的行.
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'))
问题:基于df1,df2中最相似的行是什么?
Question: Based on the df1 what is the most similar row in df2?
推荐答案
如果需要最小距离,我们可以使用 scipy.spatial.distance.cdist
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
这篇关于使用Python查找最相似的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文