1

I feel like there is some documentation I am missing, but I can't find anything on this specific example - everything is just about concatenating or stacking arrays.

I have array x and array y both of shape (2,3)

x = [[1,2,3],[4,5,6]]

y = [[7,8,9],[10,11,12]]

x = 1 2 3
    4 5 6

y = 7 8 9
    10 11 12

I want array z with shape (2,3,2) that looks like this

z = [[[1,7],[2,8],[3,9]],[[4,10],[5,11],[6,12]]]

z = [1,7] [2,8] [3,9]
    [4 10] [5 11] [6 12]

basically joins the x and y element at each position.

1
  • If you can look at the Python code for stack and dstack. They expand the array dimensions and concatenate on one axis. stack is new function in this family. Commented May 22, 2016 at 3:05

3 Answers 3

4

Sounds like the function you're looking for is stack(), using it to stack along the 3rd dimension.

import numpy as np

x = np.asarray([[1,2,3],[4,5,6]])
y = np.asarray([[7,8,9],[10,11,12]])
z = np.stack((x, y), 2)
Sign up to request clarification or add additional context in comments.

Comments

3

If you have two-dimensional matrices, you can use numpy.dstack():

z = np.dstack((x, y))

Comments

1
In [39]: z = np.concatenate((x[...,None], y[...,None]), axis=2)

In [40]: z
Out[40]: 
array([[[ 1,  7],
        [ 2,  8],
        [ 3,  9]],

       [[ 4, 10],
        [ 5, 11],
        [ 6, 12]]])

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.