【问题标题】:measuring the distance between rows of a dataframe测量数据框行之间的距离
【发布时间】:2021-05-02 12:17:27
【问题描述】:

我有一个由 472 行和 32 列组成的数据框,它看起来像这样:

2   3   0   4   2   0   0   5   2   3   3   3   2   0   5   5   3   3   3   2   2   0   2   5   3   3   3   2   2   2   0   5
2   3   0   4   2   0   0   5   2   3   3   3   2   0   5   5   3   3   3   2   2   0   2   5   3   3   3   2   2   2   0   5
2   3   0   4   2   0   0   5   2   3   3   3   2   0   5   5   3   3   3   2   2   0   2   5   3   3   3   2   2   2   0   5

这里,每一行代表一个人的 32 颗牙齿,0-5 之间的每个数字代表不同的牙齿类别。现在我想通过使用不同的距离度量(例如 MANHATTAN、EUCLID、MINKOWSKI)来测量任意 2 行之间的距离。因此,差异越小,他们就越有可能是同一个人等。

*如果我在计算这些指标之前应用 ONE-HOT-ENCODING,每行将有超过 32 列,这对我来说毫无用处。

*我还找到了cdistpdist,但是这些函数给了我元素距离的结果。但我想要的是在任意两行之间获得一个“单一结果”。

我是在尝试一些无意义的事情还是我应该怎么做才能计算出这些距离?

【问题讨论】:

标签: python pandas dataframe one-hot-encoding


【解决方案1】:

您似乎正在寻找的距离计算功能如下:

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise_distances.html

您可以将度量设置为用于 scipy.spatial.distance.pdist 的任何度量。

工作原理示例:

a = [[1,2,3,4,5,6,7,8,10]]
b = [[2,4,1,3,4,5,6,7,8]]
c = [[4,2,1,54,7,85,89,1,2]]

from sklearn.metrics import pairwise_distances

pairwise_distances(a,b)

输出将是:

数组([[4.24264069]])

类似的,输出为

pairwise_distances(a,c)

应该是:

数组([[124.87994234]])

因此,c 离 a 更远。

你可以在你的问题中使用这个逻辑。在您的情况下,以下代码 sn-p 可以解决问题:

import pandas as pd
import numpy as np

df = pd.read_csv('your_file.csv')
for i, row in df.iterrows():
    row = np.array(row)
    for j, other_row in df.iterrows():
       other_row = np.array(other_row)
       distance = pairwise_distances(np.reshape(row,(1,len(row))),np.reshape(other_row,(1,len(other_row))))
       print("Distance between row {} and {} : {}".format(i,j,distance))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 2013-10-03
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多