How to create an numpy array with shape [2, 2, 3]
, where the elements at axis 2 is another array, for example [1, 2, 3]
?
So I would like to do something like this invalid code:
a = np.arange(1, 4)
b = np.full((3, 3), a)
Resulting in an array like:
[[[ 1. 2. 3.]
[ 1. 2. 3.]]
[[ 1. 2. 3.]
[ 1. 2. 3.]]]
Could of course make the loop for filling like, but thought there may be a shortcut:
for y in range(b.shape[0]):
for x in range(b.shape[1]):
b[y, x, :] = a
Also using
np.concatenate
or it's wrappernp.vstack
If your numpy version is >= 1.10 you can use broadcast_to
This produces a view rather than copying so will be quicker for large arrays. EDIT this looks to be the result you're asking for with your demo.
Based on Divakar comment, an answer can also be:
Yet another possibility is:
There are multiple ways to achieve this. One is to use
np.full
innp.full((2,2,3), a)
as pointed out by Divakar in the comments. Alternatively, you can usenp.tile
for this, which allows you to construct an array by repeating an input array a given number of times. To construct your example you could do: