5

I'm not sure if this has been asked before but I couldn't find the solution to this seemingly simple problem. I have two arrays like so:

x = np.array([[1,2,3],[4,5,6]])
y = np.array([[1,2,3],[7,8,9]])

And I want to create a merged matrix like:

merged = [[(1,1),(2,2),(3,3)],[(4,7),(5,8),(6,9)]]

What is the fastest way to achieve this? I'm using python 2.

2
  • 3
    I think np.stack([x, y], axis=-1) (cant check now) will give you a 3D array of the shape that you want. You could then use .tolist() if you really need a list. Commented Feb 9, 2018 at 18:28
  • Do you need your innermost pair to be a tupleor does a list work as well? Commented Feb 9, 2018 at 21:31

1 Answer 1

4

stack is a newish, handy way of creating an array like this. It's like np.array but lets us specify the new axis:

In [117]: x = np.array([[1,2,3],[4,5,6]])
     ...: y = np.array([[1,2,3],[7,8,9]])
     ...: 
In [118]: x.shape
Out[118]: (2, 3)
In [119]: np.stack((x,y),axis=2)
Out[119]: 
array([[[1, 1],
        [2, 2],
        [3, 3]],

       [[4, 7],
        [5, 8],
        [6, 9]]])

Without stack you can combine the arrays on a new first axis, and then change the order of the axes:

In [120]: np.array((x,y))
Out[120]: 
array([[[1, 2, 3],
        [4, 5, 6]],

       [[1, 2, 3],
        [7, 8, 9]]])
In [121]: np.array((x,y)).transpose(1,2,0)
Out[121]: 
array([[[1, 1],
        [2, 2],
        [3, 3]],

       [[4, 7],
        [5, 8],
        [6, 9]]])

Note that a 3d array like this is not, technically, a 2d array of tuples. But for most purposes it is better than that.

stack (and dstack) expand the dimensions to the input arrays, and do a concatenate on that new dimension. In other words, they do:

In [123]: np.concatenate((x[...,None],y[...,None]),axis=-1)
Out[123]: 
array([[[1, 1],
        [2, 2],
        [3, 3]],

       [[4, 7],
        [5, 8],
        [6, 9]]])
Sign up to request clarification or add additional context in comments.

Comments

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.