Return 计算距离度量后的索引

Return index after calculating distance metric

给定一个具有 4 个特征和 1 个索引列的 DF:

df = pd.DataFrame(np.random.randint(0,100, size= (100,4)), columns=list('ABCD'))
df['index'] = range(1, len(df) + 1)

我想根据用户的输入计算曼哈顿距离。用户的输入将由 a、b、c、d 表示。函数定义如下。

def Manhattan_d(a,b,c,d):

    return (a - df['A']) + (b -df['B']) + (c - df['C']) + (d - df['D'])

当答案被 return 发给我时,它会以列表的形式出现。现在,我想找到最小值 returned 并 link 从它的来源返回索引号。

如果我做 return(min(formula)),我得到一个数字的输出,但我无法将它定位回它最初来自的索引。如果它更容易,索引代表一个类别。所以我需要找到应用公式后输出最小的类别。

希望已经清楚了。

也许更好的方法是将曼哈顿距离应用于数据帧的每一行。那时,您可以使用 .idxmin() 找到原始数据框中与您输入函数的点 a、b、c、d 最相似(曼哈顿距离最小)的点的索引。

def Manhattan_d(a,b,c,d, df):
    return df.apply(lambda row:abs(row['A']-a)+abs(row['B']-b)+abs(row['C']-c)+abs(row['D']-d), axis=1).idxmin()

注意:曼哈顿距离需要差值的绝对值,我已经包含了。

另一个注意事项:将所有变量传递给函数通常是一种很好的做法,这就是为什么我将 df 作为函数的输入。

另一种可能性是使用现有的实现,例如来自 Scikit-learn 的 DistanceMetric class。