3

Is there a more efficient way (or at least pythonic) to stack n copies of a subarray in order to create a new array?

import numpy as np

x = np.arange(4)
for i in range(n-1):
    x = hstack((x,arange(4)))

Thanks,

1 Answer 1

5
In [34]: x = np.arange(4)

In [35]: np.tile(x,(3,1))
Out[35]: 
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])

But be careful -- you may be able to use broadcasting instead of duplicating the same row over and over.

For example, suppose you have some array of shape (3,4):

In [40]: y = np.arange(12).reshape(3,4)

In [41]: y
Out[41]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

And here is your x:

In [42]: x = np.arange(4)

In [43]: x
Out[43]: array([0, 1, 2, 3])

You can add x (whose shape is (4,)) with y (whose shape is (3,4)), and NumPy will automatically "broadcast" x to shape (3,4):

In [44]: x + y
Out[44]: 
array([[ 0,  2,  4,  6],
       [ 4,  6,  8, 10],
       [ 8, 10, 12, 14]])

Compare the result with

In [45]: np.tile(x,(3,1)) + y
Out[45]: 
array([[ 0,  2,  4,  6],
       [ 4,  6,  8, 10],
       [ 8, 10, 12, 14]])

As you can see, there is no need to tile x first. In fact, by not tiling x, you save memory.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget advanced indexing and the index_tricks module instances. x[np.c_[[range(x.size)]*n]] will have the same effect as tiling, assuming x is a flat array. (Though it probably still uses more memory than direct broadcasting.)
Very concise. np.tile() was what I was looking for and the broadcasting solution was what I came here asking for.

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.