gpt4 book ai didi

python - pandas DataFrame 上的 scipy pdist()

转载 作者:太空狗 更新时间:2023-10-30 00:25:02 25 4
gpt4 key购买 nike

我有一个大型数据框(例如 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's 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

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

最佳答案

哦,我在这个 webpage 上找到了答案.显然,有一个名为 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

关于python - pandas DataFrame 上的 scipy pdist(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32946241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com