0

I'm trying to build an array of some given shape in which all elements are given by another array. Is there a function in numpy which does that efficiently, similar to np.full(), or any other elegant way, without simply employing for loops?

Example: Let's say I want an array with shape (dim1,dim2) filled with a given, constant scalar value. Numpy has np.full() for this:

my_array = np.full((dim1,dim2),value)

I'm looking for an analog way of doing this, but I want the array to be filled with another array of shape (filldim1,filldim2) A brute-force way would be this:

my_array = np.array([])
for i in range(dim1):
    for j in range(dim2):
        my_array = np.append(my_array,fill_array)
my_array = my_array.reshape((dim1,dim2,filldim1,filldim2))

EDIT

I was being stupid, np.full() does take arrays as fill value if the shape is modified accordingly:

my_array = np.full((dim1,dim2,filldim1,filldim2),fill_array)

Thanks for pointing that out, @Arne!

janosch
  • 3
  • 2

1 Answers1

0

You can use np.tile:

>>> shape = (2, 3)
>>> fill_shape = (4, 5)
>>> fill_arr = np.random.randn(*fill_shape)

>>> arr =  np.tile(fill_arr, [*shape, 1, 1])

>>> arr.shape
(2, 3, 4, 5)

>>> np.all(arr[0, 0] == fill_arr)
True

Edit: better answer, as suggested by @Arne, directly using np.full:

>>> arr = np.full([*shape, *fill_shape], fill_arr)                                               

>>> arr.shape                                                                                    
(2, 3, 4, 5)

>>> np.all(arr[0, 0] == fill_arr)                                                                
True
paime
  • 2,901
  • 1
  • 6
  • 17
  • Thanks! I have two questions: 1) What is the difference between the two solutions? And 2) Is the asterisk required here? – janosch Jul 07 '20 at 09:35
  • The `np.full` solution is better because it is 1. more explicit 2. already generalized for any number of dimensions for the `fill_arr` array. Performances are similar (`np.full` a bit faster). And, yes, the star operator is required to unpack shapes values before repacking them into a single list, see https://stackoverflow.com/a/2921893/13636407. – paime Jul 07 '20 at 10:25