【问题标题】:How to calculate the distance in Python如何在 Python 中计算距离
【发布时间】:2020-07-08 14:38:56
【问题描述】:

假设我有两个点数组,我想知道每个点之间的距离是多少。

例如:

array_1 = [p1,p2,p3,p4]
array_2 = [p5,p6]

p1 到 p6 是点,类似于 [1,1,1] (3D)

我想要的输出是

output = [[distance of p1 to p5, distance of p2 to p5, ... distance of p4 to p5], 
          [distance of p1 to p6, distance of p2 to p6, ... distance of p4 to p6]]

如果我想使用 numpy,最好的方法是什么?

【问题讨论】:

    标签: python-3.x numpy euclidean-distance


    【解决方案1】:

    此答案并非专门针对 numpy 数组,但可以轻松扩展以包含它们。模块 itertools.product 是你的朋友。

    # Fill this with your formula for distance
    def calculate_distance(point_1, point_2):
        distance = ...
        return distance
    
    # The itertools module helps here
    import itertools
    array_1, array_2 = [p1, p2, p3, p4], [p5, p6]
    
    # Initialise list to store answers
    distances = []
    
    # Iterate over every combination and calculate distance
    for i, j in itertools.product(array_1, array_2):
        distances.append(calculate_distance(i, j)
    

    【讨论】:

      【解决方案2】:

      可以先将两个数组排列成m×1×31×n×3的形状,然后减去坐标:

      delta = array_1[:,None] - array_2
      

      接下来我们可以对坐标的差值求平方,并计算和,然后我们可以计算平方路由:

      distances = np.sqrt((delta*delta).sum(axis=2))
      

      现在distances 是一个 m×n 矩阵,其中第 ij 个元素是第 i 个元素之间的距离第一个数组,以及第二个数组的第 j 个元素。

      例如,如果我们有数据:

      >>> array_1 = np.arange(12).reshape(-1,3)
      >>> array_2 = 2*np.arange(6).reshape(-1,3)
      

      我们得到结果:

      >>> delta = array_1[:,None] - array_2
      >>> distances = np.sqrt((delta*delta).sum(axis=2))
      >>> distances
      array([[ 2.23606798, 12.20655562],
             [ 3.74165739,  7.07106781],
             [ 8.77496439,  2.23606798],
             [13.92838828,  3.74165739]])
      

      array_1 的第一个元素具有坐标 (0,1,2),array_2 的第二个元素具有坐标 (6,8,10)。因此距离为:

      >>> np.sqrt(6*6 + 7*7 + 8*8)
      12.206555615733702
      

      这是我们在distances 数组中看到的distances[0,1]

      上述函数方法可以计算任意维数的欧几里得距离。鉴于array_1array_2 的点具有相同的维数(1D、2D、3D 等),这可以计算点的距离。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 2019-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-20
        • 2021-04-06
        相关资源
        最近更新 更多