我有一个包含数百万行的数据框“数据”。每行都有坐标('x','y'),我想以Python可以提供的最有效的方式计算连续的坐标对之间的距离。并行化在这里会有帮助吗?
我在这里看到建议使用 cython 的方法。不过我只想看到 python 解决方案。
这是我的数据片段
points =
[(26406, -6869),
(27679, -221),
(27679, -221),
(26416, -6156),
(26679, -578),
(26679, -580),
(27813, -558),
(26254, -1097),
(26679, -580),
(27813, -558),
(28258, -893),
(26253, -1098),
(26678, -581),
(27811, -558),
(28259, -893),
(26252, -1098),
(27230, -481),
(26679, -582),
(27488, -5849),
(27811, -558),
(28259, -893),
(26250, -1099),
(27228, -481),
(26679, -582),
(27488, -5847),
(28525, -1465),
(27811, -558),
(28259, -892)]
我相信我的第一种使用 for-loop 的方法绝对可以改进:
from scipy.spatial import distance
def comp_dist(points):
size =len(points)
d = 0
i=1
for i in range(1,size):
if i%1000000==0:
print i
# print "i-1:", points[i-1]
# print "i: ", points[i]
dist = distance.euclidean(points[i-1],points[i])
d= d+dist
print d
distance = comp_dist(points)
感谢您提前的答复。
最佳答案
你说的是 python,但由于你已经使用 scipy 进行距离计算,我认为 numpy 解决方案是可以的。
在我的笔记本电脑上,对 2800 万点 numpy 数组使用矢量化、单线程操作仅需 1 秒。使用32位整数数据类型,该数组占用内存约200MB。
import numpy as np
points = [(26406, -6869), ..., (28259, -892)]
# make test array my repeating the 28-element points list 1M times
np_points = np.array(points*1000000, dtype='int32')
# use two different slices (offset by 1) from resulting array;
# execution of next line takes ~1 second
dists = np.sqrt(np.sum((np_points[0:-2] - np_points[1:-1])**2, axis=1))
print(dists.shape)
(27999998,)
print(dists[:28])
[ 6.76878372e+03 0.00000000e+00 6.06789865e+03 5.58419672e+03
2.00000000e+00 1.13421338e+03 1.64954600e+03 6.69263775e+02
1.13421338e+03 5.57000898e+02 2.01545280e+03 6.69263775e+02
1.13323343e+03 5.59400572e+02 2.01744244e+03 1.15636197e+03
5.60180328e+02 5.32876815e+03 5.30084993e+03 5.59400572e+02
2.01953386e+03 1.15689585e+03 5.58213221e+02 5.32679134e+03
4.50303153e+03 1.15431581e+03 5.58802291e+02 6.25764636e+03]
关于python - 使用 Python 代码并行计算两点之间距离的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37790062/