Gautam Sreekumar
Gautam Sreekumar

Reputation: 564

Creating 4D numpy array by repeating values from 2D numpy array

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?

Upvotes: 3

Views: 1466

Answers (3)

Divakar
Divakar

Reputation: 221754

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

Upvotes: 4

MSeifert
MSeifert

Reputation: 152860

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.

Upvotes: 3

Gautam Sreekumar
Gautam Sreekumar

Reputation: 564

i got the answer.

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

this should work fine

Upvotes: 0

Related Questions