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

      

+3


source to share


4 answers


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])

      

+3


source


If your numpy version> = 1.10 you can use broadcast_to

a = np.arange(1,4)
a.shape = (1,1,3)
b = np.broadcast_to(a,(2,2,3))

      



This creates a view, not a copy, so it will be faster for large arrays. EDIT this looks like the result you are asking with your demo.

+2


source


Based on Divakar's comment, the answer could also be:

import numpy as np
np.full([2, 2, 3], np.arange(1, 4))

      

Another possibility:

import numpy as np
b = np.empty([2, 2, 3])
b[:] = np.arange(1, 4)

      

+2


source


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]]])

      

+1


source







All Articles