7

我有一个大数据框(例如 15k 个对象),其中每一行是一个对象,列是数字对象特征。它的形式是:

df = pd.DataFrame({ 'A' : [0, 0, 1],
                    'B' : [2, 3, 4],
                    'C' : [5, 0, 1],
                    'D' : [1, 1, 0]},
                    columns= ['A','B', 'C', 'D'], index=['first', 'second', 'third'])

我想计算所有对象(行)的成对距离并读到scipy 的 pdist()函数由于其计算效率是一个很好的解决方案。我可以简单地调用:

res = pdist(df, 'cityblock')
res
>> array([ 6.,  8.,  4.])

并看到该res数组包含以下顺序的距离:[first-second, first-third, second-third].

我的问题是如何以矩阵、数据框或(不太理想的)dict 格式获取它,以便我确切知道每个距离值属于哪对,如下所示:

       first second third
first    0      -     -
second   6      0     -
third    8      4     0

最终,我认为将距离矩阵作为 pandas DataFrame 可能会很方便,因为我可以对每行应用一些排名和排序操作(例如,找到最接近 object 的前 N ​​个对象first)。

4

1 回答 1

20

哦,我在这个网页上找到了答案。显然,有一个名为squareform()的专用函数。暂时不要删除我的问题,以防它可能对其他人有帮助。

from scipy.spatial.distance import squareform
res = pdist(df, 'cityblock')
squareform(res)
pd.DataFrame(squareform(res), index=df.index, columns= df.index)
>>        first  second  third
>>first       0       6      8
>>second      6       0      4
>>third       8       4      0
于 2015-10-05T10:43:47.877 回答