numpy-将x,y坐标的2D数组转换为坐标之间距离的平面数组 [英] Numpy - transform 2D array of x,y coordinates into flat array of distance between coordinates

查看:153
本文介绍了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()))

这篇关于numpy-将x,y坐标的2D数组转换为坐标之间距离的平面数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆