Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining two 2D numpy arrays into a single 2D array of 2-tuples

I have two 2D numpy arrays like this, representing the x/y distances between three points. I need the x/y distances as tuples in a single array.

So from:

x_dists = array([[ 0, -1, -2],
                 [ 1,  0, -1],
                 [ 2,  1,  0]])

y_dists = array([[ 0, -1, -2],
                 [ 1,  0, -1],
                 [ 2,  1,  0]])

I need:

dists = array([[[ 0,  0], [-1, -1], [-2, -2]],
               [[ 1,  1], [ 0,  0], [-1, -1]],
               [[ 2,  2], [ 1,  1], [ 0,  0]]])

I've tried using various permutations of dstack/hstack/vstack/concatenate, but none of them seem to do what I want. The actual arrays in code are liable to be gigantic, so iterating over the elements in python and doing the rearrangement "manually" isn't an option speed-wise.

Edit: This is what I came up with in the end: https://gist.github.com/807656

like image 746
Zarkonnen Avatar asked Feb 02 '11 11:02

Zarkonnen


2 Answers

import numpy as np
dists = np.vstack(([x_dists.T], [y_dists.T])).T

returns dists like you wanted them. Afterwards it is not "a single 2D array of 2-tuples", but a normal 3D array where the third axis is the concatenation of the two original arrays.

You see:

dists.shape # (3, 3, 2)
like image 198
eumiro Avatar answered Sep 21 '22 00:09

eumiro


numpy.rec.fromarrays([x_dists, y_dists], names='x,y')
like image 37
jfs Avatar answered Sep 20 '22 00:09

jfs