Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array from n copies of subarray in python

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,

like image 646
poeticcapybara Avatar asked Jan 22 '26 16:01

poeticcapybara


1 Answers

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.

like image 176
unutbu Avatar answered Jan 24 '26 09:01

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!