Reputation: 575
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,
Upvotes: 3
Views: 1120
Reputation: 879591
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.
Upvotes: 5