关于pandas DataFrame的scipy pdist()

Zhu*_*arb 6 python scipy pandas pdist

我有一个大型数据框(例如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'])
Run Code Online (Sandbox Code Playgroud)

我想计算所有对象(行)的成对距离,并且由于其计算效率,读取scipy的pdist()函数是一个很好的解决方案.我可以简单地打电话:

res = pdist(df, 'cityblock')
res
>> array([ 6.,  8.,  4.])
Run Code Online (Sandbox Code Playgroud)

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

我的问题是如何在矩阵,数据帧或(不太理想的)dict格式中得到它,所以我确切地知道每个距离值属于哪一对,如下所示:

       first second third
first    0      -     -
second   6      0     -
third    8      4     0
Run Code Online (Sandbox Code Playgroud)

最后,我认为将距离矩阵作为pandas DataFrame可能很方便,因为我可以对每行应用一些排序和排序操作(例如,找到最靠近对象的N个最近的对象first).

Zhu*_*arb 18

哦,我在这个网页上找到了答案.显然,有一个名为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
Run Code Online (Sandbox Code Playgroud)