【问题标题】:Manhattan Distance between (P, Q) and (R,)(P, Q) 和 (R,) 之间的曼哈顿距离
【发布时间】:2018-10-29 20:34:00
【问题描述】:

我正在研究曼哈顿距离。它适用于简单的 for 循环。但我试图避免这种 for 循环。

import numpy as np
import random
A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]
for i in range(10):
    dist = sum(abs(A[i]-B))
    print("Distances: ", dist)

还有比这更好的方法吗?例如使用高级索引.. 谢谢你的指导。

【问题讨论】:

  • 有趣的是,我尝试使用scipy.spatial.distance.cityblock 来计算曼哈顿距离,结果它比您的循环慢,更不用说@sacul 提供的更好的解决方案了。
  • @XiaoyuLu,我只是在更新我的答案以包含scipy 方法。它也很好用,但我更喜欢使用numpy,因为在这种情况下算法非常简单,并且它避免了额外的导入
  • @sacul 同意 100%。那里有很好的解决方案! cdistnumpy 慢,并且需要额外的导入。带回家的消息是,预先编写的库可能不一定比您自己构建的代码快。

标签: python arrays python-3.x numpy


【解决方案1】:

numpy

您可以在 numpy 中执行此操作:

>>> np.sum(np.abs(A-B), axis=1)
array([10,  6,  9,  9,  7,  7,  9,  8, 14,  8])

将此与循环的输出进行比较:

Distances:  10
Distances:  6
Distances:  9
Distances:  9
Distances:  7
Distances:  7
Distances:  9
Distances:  8
Distances:  14
Distances:  8

替代方案:scipy

如果你愿意,你也可以使用scipy(不过我个人更喜欢numpy 方法):

from scipy.spatial.distance import cdist

>>> cdist(A,np.array(B).reshape(1,-1), metric='cityblock')
array([[10.],
       [ 6.],
       [ 9.],
       [ 9.],
       [ 7.],
       [ 7.],
       [ 9.],
       [ 8.],
       [14.],
       [ 8.]])

【讨论】:

    【解决方案2】:

    您不会使用弧度或度数来计算结果吗?这应该适合你。

    from math import sin, cos, sqrt, atan2, radians
    
    # approximate radius of earth in km
    R = 6373.0
    
    lat1 = radians(40.7619087)
    lon1 = radians(-73.9690218)
    lat2 = radians(40.760178)
    lon2 = radians(-74.0037083)
    
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    
    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    
    distance = R * c
    
    print("Result:", distance)
    print("Should be:", distance, "mi")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多