python - 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,所以任何想法都将不胜感激。
谢谢!
解决方案
一种使用方式numpy.linalg.norm
:
dist = np.linalg.norm(df - df_input.to_numpy(), axis=1)
indices = np.argwhere(dist == min(dist))
输出:
array([[0]], dtype=int64)
推荐阅读
- react-native - 为什么我的 onEnter 道具没有被触发?(react-native-router-flux v4)
- android - 调用lifecycle.addObserver 后出现内存泄漏
- r - 在数据框中的组内按时间向后编号代数(gen:0、-1、-2 等)
- javascript - Azure Maps 上是否有任何绘图功能?
- c# - 如何在 LINQ 中将行转换为列
- elasticsearch - ElasticSearch 有什么好的布尔查询解析器吗?
- c++ - 通过索引运算符插入 boost::program_options::variables_map
- mockito - 由于控制器方法内部的方法调用,MockMvc 失败
- angular - 在我的函数 ngDoCheck() Angular 中关闭 matDialog 时出现问题
- python - 使用 Python 从字符串中提取值