首页 > 解决方案 > Pandas 根据输入在数据框中找到最匹配的 n 行

问题描述

抱歉,如果有人问过这种事情。我一直无法完全找到适合我需要的东西。

这是我正在使用的示例数据集:

年龄 高度 重量
25 70 120
27 50 160
34 66 140
29 40 170
27 50 160
34 66 140
29 40 170
27 50 160
34 66 140

等等

“用户”将能够输入他们的年龄、身高和体重作为输入。我编写了一个简单的类来保存此输入并将其转换为单独的数据框:

class new_data:
    def __init__(self, Age, Height, Bra, Weight, Bust, Waist, Hips):
        self.Age = Age
        self.Height = Height
        self.Weight = Weight
        
    def for_dict(self):
        return {
            'Age': self.Age,
            'Height': self.Height,
            'Weight': self.Weight,
        }

test = [new_data(Age = 20, Height = 30, Weight = 102] #sample data
df_input = pd.DataFrame.from_records([i.for_dict() for i in test])

我希望能够获取该 df_input,并尝试从我的初始数据集中找到最匹配的行,然后作为反馈提供给“用户”。我一直在思考是否要单独访问每一列,找到一些接近的匹配项,然后继续尝试基于该排序的匹配项。我也希望能够在流程结束时呈现一种百分比匹配。

我仍在学习 Python,所以任何想法都将不胜感激。

谢谢!

标签: pythonpandasdataframe

解决方案


一种使用方式numpy.linalg.norm

dist = np.linalg.norm(df - df_input.to_numpy(), axis=1)
indices = np.argwhere(dist == min(dist))

输出:

array([[0]], dtype=int64)

推荐阅读