How can I create or fill a numpy array with another array?
How can I create a numpy array with a shape [2, 2, 3]
where the elements on axis 2 are 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)
The result in an array is like:
[[[ 1. 2. 3.]
[ 1. 2. 3.]]
[[ 1. 2. 3.]
[ 1. 2. 3.]]]
It is possible, of course, to create a loop to fill, but perhaps a shortcut exists:
for y in range(b.shape[0]):
for x in range(b.shape[1]):
b[y, x, :] = a
source to share
There are several ways to achieve this. One of them is to use np.full
in np.full((2,2,3), a)
, as indicated in the comments of Divakar. Alternatively, you can use np.tile
for this, which allows you to construct an array by iterating over the input array a certain number of times. To build your example, you can do:
import numpy as np
np.tile(np.arange(1, 4), [2, 2, 1])
source to share
Also using np.concatenate
or wrappernp.vstack
In [26]: a = np.arange(1,4)
In [27]: np.vstack([a[np.newaxis, :]]*4).reshape(2,2, 3)
Out[27]:
array([[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]]])
In [28]: np.concatenate([a[np.newaxis, :]]*4, axis=0).reshape(2,2, 3)
Out[28]:
array([[[1, 2, 3],
[1, 2, 3]],
[[1, 2, 3],
[1, 2, 3]]])
source to share