我正在尝试创建一个大小为6 * n的数组,这样对于数组中每批6个单元格,我将得到以下整数值:
a = [n-2, n-1,n,n,n+1,n+1,n+2,n+3]
我能想到的平庸方式是使用这个例程:
a = []
for i in xrange(n):
np.append(a,[n-2, n-1,n,n,n+1,n+1,n+2,n+3])
但有更聪明更快的方法吗?
答案 0 :(得分:3)
您可以使用numpy.tile
:
>>> n = 6
>>> arr = np.array([n-2, n-1, n, n, n+1, n+1, n+2, n+3])
>>> np.tile(arr, n)
array([4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8,
9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7, 8, 9, 4, 5, 6, 6, 7, 7,
8, 9])
# Reshape to get the desired output
>>> np.tile(arr, n).reshape(n, arr.size)
array([[4, 5, 6, 6, 7, 7, 8, 9],
[4, 5, 6, 6, 7, 7, 8, 9],
[4, 5, 6, 6, 7, 7, 8, 9],
[4, 5, 6, 6, 7, 7, 8, 9],
[4, 5, 6, 6, 7, 7, 8, 9],
[4, 5, 6, 6, 7, 7, 8, 9]])