11

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

2
  • 1
    Is is just a coincidence that x_dist and y_dist are the same? Also what is the meaning of negative distance in your app? Would _dist allways be 'symmetric', but uppertridiagonal part just negative? How many points are you expecting to handle? What is the purpose of this stacking of arrays? Would the elements be in 'optimal' order for further calculations? Just some toughts, thanks Commented Feb 2, 2011 at 13:26
  • It's coincidence. The example points are (0, 0), (1, 1), (2, 2) for sanity's sake. _dist is indeed symmetric. The purpose of stacking the arrays is that I can use them to move the points around. See linked gist. Commented Feb 2, 2011 at 14:07

2 Answers 2

13
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)
Sign up to request clarification or add additional context in comments.

1 Comment

That's indeed what I wanted. I fear that my usage of the term "2D array of 2-tuples" was rather misleading. :(
8
numpy.rec.fromarrays([x_dists, y_dists], names='x,y')

2 Comments

Brilliant! That's exactly what I wanted. So, um, seeing as you seem to know about numpy, is the function I edited in a sane way of calculating these pairwise distances?
Edit: Actually, this doesn't give me an array I know how to do anything with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.