Below the Radar - 1 year ago 90
Python Question

# Numpy - transform 2D array of x,y coordinates into flat array of distance between coordinates

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.

For instance:

``````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)
``````

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)
``````

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

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

Another approach with `slicing` to replicate the differentiation -

``````np.hstack((arr[0], (arr[:-1,:] - arr[1:,:]).ravel()))
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download