【问题标题】:How to calculate sum of Euclidean distances from one datapoint to all other datapoints from pandas dataframe?如何计算熊猫数据帧中一个数据点到所有其他数据点的欧几里得距离总和?
【发布时间】:2018-04-19 17:12:22
【问题描述】:

我有以下熊猫数据框:

import pandas as pd
import math

df = pd.DataFrame()
df['x'] = [2, 1, 3]
df['y'] = [2, 5, 6]
df['weight'] = [11, 12, 13]
print(df)

     x    y   weight   
 0   2    2       11       
 1   1    5       12       
 2   3    6       13       

假设这3个节点分别称为{a, b, c}。我想计算一个节点到所有其他节点的总欧几里得距离乘以其权重,如下:

Sum = 11(d(a,b)+d(a,c)) + 12(d(b,a)+d(b,c)) + 13(d(c,a)+d(c,b))

【问题讨论】:

  • 你想要一个程序吗?你还有什么想要的吗?请展示你的努力,这个问题需要一个复杂的解决方案。
  • 另外,请注意您的数据中没有d 标签。
  • @cᴏʟᴅsᴘᴇᴇᴅ d(a, b) 表示节点 a 到节点 b 的欧式距离。

标签: python pandas dataframe euclidean-distance


【解决方案1】:

使用SciPy's cdist -

In [72]: from scipy.spatial.distance import cdist

In [73]: a = df[['x','y']].values

In [74]: w = df.weight.values

In [100]: cdist(a,a).sum(1) * w
Out[100]: array([ 80.13921614,  64.78014765,  82.66925684])

我们还可以使用同一 SciPy 方法中的 pdistsquareform 的组合来替换那里的 cdist

用这些实际值验证 -

In [76]: from scipy.spatial.distance import euclidean

In [77]: euclidean([2,2],[1,5])*11 + euclidean([2,2],[3,6])*11
Out[77]: 80.139216143646451

In [78]: euclidean([1,5],[2,2])*12 + euclidean([1,5],[3,6])*12
Out[78]: 64.78014765201803

In [80]: euclidean([3,6],[2,2])*13 + euclidean([3,6],[1,5])*13
Out[80]: 82.669256840526856

【讨论】:

  • 非常感谢。这真的对我有帮助:) 无论如何,如果节点数是 1000,这个程序会工作吗?
  • @arizamoona 取决于系统 RAM。但这在体面大小的 RAM 上应该没问题。使用我的 16 GB 设置,我可以运行 10000 节点,只是为了给你一个估计。
  • 哦,你的意思是如果节点数为 1000 或更多,这个计算将需要很长时间才能运行?在您看来,对于 1000 个节点,这个计算需要多少秒/分钟?差不多就可以了。
  • @arizamoona 再次取决于设置。为什么不在你的最后尝试呢?时间应与数据集大小成正比。
  • 我明白了。再次感谢你。你是如此善良和乐于助人:)
猜你喜欢
  • 2018-05-26
  • 2020-09-15
  • 2021-01-13
  • 2014-04-09
  • 2018-04-05
  • 2019-02-24
  • 2020-06-19
  • 2019-09-30
相关资源
最近更新 更多