44

I have an array A that has shape (480, 640, 3), and an array B with shape (480, 640).

How can I append these two as one array with shape (480, 640, 4)?

I tried np.append(A,B) but it doesn't keep the dimension, while the axis option causes the ValueError: all the input arrays must have same number of dimensions.

2 Answers 2

55

Use dstack:

>>> np.dstack((A, B)).shape
(480, 640, 4)

This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.

Otherwise, to use append or concatenate, you'll have to make B three dimensional yourself and specify the axis you want to join them on:

>>> np.append(A, np.atleast_3d(B), axis=2).shape
(480, 640, 4)
Sign up to request clarification or add additional context in comments.

5 Comments

Or to use the most basic methods: np.concatenate(A, B[...,None], axis=2)
@hpaulj Getting error TypeError: concatenate() takes at most 2 arguments (3 given)
@piepi, did you look at the concatenate docs? They have priority over my old comments. In any case, I should have written np.concatenate([A, B[...,None]], axis=2). That is, put the arrays in a list
@piepi, did you look at the concatenate docs? They have priority over my old comments. In any case, I should have written np.concatenate([A, B[...,None]], axis=2). That is, put the arrays in a list
Coming from Matlab, holy **** why do I have to be googling for 15 minutes to find this. It should be obvious that concatenate( <M x N x Q>, <M x N x 1>) should result in <M x N x Q + 1>.
3

using np.stack should work but the catch is both arrays should be of 2D form.

np.stack([A,B])

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.