numpy-将x,y坐标的2D数组转换为坐标之间距离的平面数组

问题描述:

我想使用numpy将x,y坐标的2D数组转换为前一个坐标之间的距离的平面数组.请注意,应该将第一对x/y坐标保留在输出数组中,以作为以后重建坐标的参考.

I would like to use numpy to convert a 2D array of x,y coordinates into a flat array of distance of each coordinates between the previous. Note that the first pair of x/y coordinates should be keeped in the output array as reference to rebuild the coordinates later.

此过程的目的是减小阵列的大小,以提高网络上的共享速度.

The aim of this process is to reduce the size of the array to increase the speed of sharing on the network.

例如:

input = [[-8081441,5685214], [-8081446,5685216], [-8081442,5685219], [-8081440,5685211], [-8081441,5685214]]
output = [-8081441, 5685214, 5, -2, -4, -3, -2, 8, 1, -3]

def parseCoords(coords):
    #keep the first x,y coordinates
    parsed = [int(coords[0][0]), int(coords[0][1])]
    for i in xrange(1, len(coords)):
        parsed.extend([int(coords[i-1][0]) - int(coords[i][0]), int(coords[i-1][1]) - int(coords[i][1])])
    return parsed

parsedCoords = parseCoords(input)

为了提高性能,是否可以使用numpy数组执行与此函数相同的操作?

Is it possible, for increased performance, to use numpy arrays to do the same thing that this function?

首先,为了提高性能,让我们将列表输入(如果还不是数组的话)转换为数组,就像这样-

First off, for performance, let's convert the list input as an array if its not an array already, like so -

arr = np.asarray(input).astype(int)

现在,我们将采用 np.diff -

Now, we would have one approach with np.diff -

np.hstack((arr[0], (-np.diff(arr, axis=0)).ravel()))

另一种使用> 复制差异-

np.hstack((arr[0], (arr[:-1,:] - arr[1:,:]).ravel()))