我有一个大数据框(例如 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
)。