python - 如何根据行获取数据框中行的最佳最近值?

标签 python python-3.x pandas dataframe scikit-learn

我有数据集

Food Name          Protein  Calorie Carbohydrate    Calcium
Butter, salted     0.85     717       0.06          24.0
Butter, whipped    0.49     718       2.87          23.0
Butter oil         0.28     876       0.00          4.0
Cheese, blue       21.40    353       2.34          528.0
Cheese, brick      23.24    371       2.79          674.0

还有一行...

Protein Calorie Carbohydrate    Calcium
56      2200    130             8

这里哪一行与该行最匹配?

最佳答案

我相信你需要:

#get diffrence of matched columns, convert to absolute
df3 = df1[df2.columns].sub(df2.iloc[0]).abs()

#compare by minimal values, count them by sum
s = df3.eq(df3.min()).sum(axis=1)

#filter rows with maximal count
df = df1[s.eq(s.max())]
print (df)
    Food Name  Protein  Calorie  Carbohydrate  Calcium
2  Butter oil     0.28      876           0.0      4.0

关于python - 如何根据行获取数据框中行的最佳最近值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59319932/

相关文章:

python - 如何在 cherrypy 中使用全局变量?

Python 多重处理 for 循环/其他可迭代对象

python-3.x - xml.etree.ElementTree >> Python >> 如何访问子元素并进行断言

python - 从 pandas 数据框中删除已知的异常值

python - 如何计算Python pandas中最后五行的平均值

python - Pandas:将多索引列标题转换为普通列标题?

cx_Freeze 后 Python 脚本未写入文件

python - Python 中的并行数据处理

python - boost python 库链接问题 -- undefined symbol

python - Python 中的 MySQL。插入查询不起作用