2

I have a 3x2x2 numpy array and I want to join another array to it that is 3x2 so that my new array is then 3x2x3. I have been trying with stack and concatenate but I keep getting ValueError: all input arrays must have the same shape. The existing array is like follows

array([[[1, 1],
        [2, 2]],

       [[3, 3],
        [4, 4]],

       [[5, 5],
        [6, 6]]])

And I wish to join another array that is like so:

array([[1, 2],
       [3, 4],
       [5, 6]])

The output would be like so:

array([[[1., 1., 1.],
        [2., 2., 2.]],

       [[3., 3., 3.],
        [4., 4., 4.]],

       [[5., 5., 5.],
        [6., 6., 6.]]])

I am not sure if I have written the output correctly as the way numpy displays matrices with 3 dimnsions confuses me- The result should have the shape(3,2,3). I wish to do this iteratively so that I can keep extending the matrix so that the shape would be (3,2,4) then (3,2,5) then (3,2,6) etc...

3
  • 2
    And the desired output is ..? Commented Jan 28, 2019 at 16:05
  • You quoted the stack error message, but concatenate complained all the input arrays must have same number of dimensions. Right? Do you know how to correct that? How to add a dimension to the (3,2) array? Commented Jan 28, 2019 at 16:49
  • Why do you want to do this iteratively? Why not collect al the (3,2) arrays into a list, and join them with one concatenate? Commented Jan 28, 2019 at 16:50

1 Answer 1

2

Reshape the 3x2 array to 3x2x1 and then do dstack:

a = array([[[1, 1],
            [2, 2]],
           [[3, 3],
            [4, 4]],
           [[5, 5],
            [6, 6]]])

b = array([[1, 2],
           [3, 4],
           [5, 6]])

np.dstack((a, b[...,None]))
#array([[[1, 1, 1],
#        [2, 2, 2]],
#       [[3, 3, 3],
#        [4, 4, 4]],
#       [[5, 5, 5],
#        [6, 6, 6]]])

np.dstack((a, b[...,None])).shape
#(3, 2, 3)

Or np.concatenate along the last axis:

np.concatenate((a, b[...,None]), axis=-1)
Sign up to request clarification or add additional context in comments.

2 Comments

Can please you address me to a reference for b[...,None]? I tried b.reshape(3,2,1), but seem not working. It seems that just np.dstack((a,b)) works.
You can see numpy indexing where there's a few examples for np.newaxis or None. and also b.reshape(3,2,1) should work the same way as b[...,None]

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.