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?

0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

you don't need the trailing , in your tuple (20, 20,) - that's only needed for one-element-tuples. :)
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.
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.

Comments

0

i got the answer.

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

this should work fine

7 Comments

If you are using initialized array2, you don't need that copy().
and you don't need all the :, :, :, :, one simple : would also work (by broadcasting).
Thank you Divakar and MSeifert for the suggestions.
Going with this copying method would be in-efficient as you are making that unnecessary copy.
@Gautam That copy made with array1.copy() is un-necessary. You are assigned values into array2, which could directly be fed from array1 itself, rather than making a copy of array1 and then feeding from it. Thus, you could simply do : array2[:, :, :, :] = array1.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.