3

I have a 2D numpy array, say array1 with values. array1 is of dimensions 2x4. I want to create a 4D numpy array array2 with dimensions 20x20x2x4 and I wish to replicate the array array1 to get this array.

That is, if array1 was

[[1, 2, 3, 4],
 [5, 6, 7, 8]]

I want

array2[0, 0] = array1
array2[0, 1] = array1
array2[0, 2] = array1
array2[0, 3] = array1
# etc.

How can I do this?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
Gautam Sreekumar
  • 536
  • 1
  • 9
  • 20

3 Answers3

4

One approach with initialization -

array2 = np.empty((20,20) + array1.shape,dtype=array1.dtype)
array2[:] = array1

Runtime test -

In [400]: array1 = np.arange(1,9).reshape(2,4)

In [401]: array1
Out[401]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

# @MSeifert's soln
In [402]: %timeit np.tile(array1, (20, 20, 1, 1))
100000 loops, best of 3: 8.01 µs per loop

# Proposed soln in this post
In [403]: %timeit initialization_based(array1)
100000 loops, best of 3: 4.11 µs per loop

# @MSeifert's soln for READONLY-view
In [406]: %timeit np.broadcast_to(array1, (20, 20, 2, 4))
100000 loops, best of 3: 2.78 µs per loop
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • you don't need the trailing `,` in your tuple `(20, 20,)` - that's only needed for one-element-tuples. :) – MSeifert Feb 27 '17 at 14:55
  • The timings should be treated with care (I get roughly the same results for small arrays). Because as far as I know is `np.broadcast_to` a constant time operation. – MSeifert Feb 27 '17 at 15:25
3

There are two easy ways:

np.broadcast_to:

array2 = np.broadcast_to(array1, (20, 20, 2, 4))  # array2 is a READONLY-view

and np.tile:

array2 = np.tile(array1, (20, 20, 1, 1))          # array2 is a normal numpy array

If you don't want to modify your array2 then np.broadcast_to should be really fast and simple. Otherwise np.tile or assigning to a new allocated array (see Divakars answer) should be preferred.

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

i got the answer.

array2[:, :, :, :] = array1.copy()

this should work fine

Gautam Sreekumar
  • 536
  • 1
  • 9
  • 20