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,

4

1 回答 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]])

但要小心——您可以使用广播而不是一遍又一遍地复制同一行。

例如,假设您有一些形状 (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]])

这是你的x

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

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

您可以将x(其形状为(4,))与y(其形状为(3,4))相加,NumPy 将自动“广播”x为形状(3,4):

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

将结果与

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

如您所见,没有必要tile x先。事实上,通过平铺x,您可以节省内存。

于 2013-07-30T12:03:16.560 回答