使用 Python 查找最相似的行

Find the most similar row using Python

我有两个数据框(df1 和 df2)。在 df1 中,我用一组值存储一行,我想在 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 中最相似的行是什么?

如果你想要最小距离,我们可以使用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

用df1减去df2,计算每一行的范数。找到最小的范数并解决问题。

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()]

可读性强,速度快。