【问题标题】:How to get best nearest value of row in dataframe based on a row?如何根据行获得数据框中行的最佳最近值?
【发布时间】:2020-04-06 18:01:01
【问题描述】:

我拥有的数据集

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

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

【问题讨论】:

  • 您需要提供更多示例来说明您希望通过预期输出实现的目标
  • 如何定义“最佳匹配”?
  • 一种食物的营养最接近给定的营养行...

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


【解决方案1】:

我猜,您可以使用Cosine similarity 来表示给定向量与给定矩阵之间的距离。找到 abs 不是一个好方法,因为数据没有标准化。

    import numpy as np
    from numpy import dot
    from numpy.linalg import norm

    a = np.array([[0.85,717,0.06,24.0],[0.49,718,2.87,23.0],[0.28,876,0.00,4.0],[21.40,353,2.34,528.0],[23.24,371,2.79,674.0]])
    b = np.array([56,2200,130,8])
    cos_sim = dot(a, b)/(norm(a)*norm(b))

    selected_row = np.argmin(cos_sim) + 1 
    print ("Distances:")
    print (cos_sim)
    print ("Selected_row: " + str(selected_row))

【讨论】:

  • @H R shuvo 您能否验证答案并接受,如果这是您正在寻找的。如果不让我们知道如何帮助您?
【解决方案2】:

我相信你需要:

#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

【讨论】:

  • 我认为您需要将.abs() 添加到比较逻辑中,因为原则上这些值可能为负数。
猜你喜欢
  • 1970-01-01
  • 2019-10-02
  • 2017-09-15
  • 2021-10-11
  • 1970-01-01
  • 2023-02-07
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多