29

During preparing data for NumPy calculate. I am curious about way to construct:

myarray.shape => (2,18,18)

from:

d1.shape => (18,18)
d2.shape => (18,18)

I try to use NumPy command:

hstack([[d1],[d2]])

but it looks not work!

4 Answers 4

44

Just doing d3 = array([d1,d2]) seems to work for me:

>>> from numpy import array
>>> # ... create d1 and d2 ...
>>> d1.shape
(18,18)
>>> d2.shape
(18,18)
>>> d3 = array([d1, d2])
>>> d3.shape
(2, 18, 18)
Sign up to request clarification or add additional context in comments.

3 Comments

I have one question similar. If I have already got the d3 with shape(2,18,18) and I want to add another 2-d array d4 (18x18) into d3 to make 3-d array(3,18,18). What should I do?
You simply vstack(d3, d4[np.newaxis,...]), as in my answer.
It must be vstack((d3, d4[np.newaxis,...])). Two '(( ))' are needed.
22

hstack and vstack do no change the number of dimensions of the arrays: they merely put them "side by side". Thus, combining 2-dimensional arrays creates a new 2-dimensional array (not a 3D one!).

You can do what Daniel suggested (directly use numpy.array([d1, d2])).

You can alternatively convert your arrays to 3D arrays before stacking them, by adding a new dimension to each array:

d3 = numpy.vstack([ d1[newaxis,...], d2[newaxis,...] ])  # shape = (2, 18, 18)

In fact, d1[newaxis,...].shape == (1, 18, 18), and you can stack both 3D arrays directly and get the new 3D array (d3) that you wanted.

1 Comment

np.vstack([a[np.newaxis,...],b[np.newaxis,...]]) worked like charm! Thanks.
13
arr3=np.dstack([arr1, arr2])

arr1, arr2 are 2d array shape (256,256), arr3: shape(256,256,2)

1 Comment

Up for this, because it works for joining RGB channels on images too, as the final shape must be (height,width,3).
8

You can use the np.stack() function like this:

>>> d3 = np.stack([d1, d2])
>>> d3.shape
(2, 18, 18)

This is more concise than using np.vstack and (in my eyes) more explicit than just using np.array.

Additionally you can also specify the axis along which the arrays get joined. So if you wanted them joined along the last axis instead of the first, you could use:

>>> d3 = np.stack([d1, d2], axis=-1)
>>> d3.shape
(18, 18, 2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.