这是一种基于对输入数组进行零填充的有效方法。每个代码步骤中的内联 cmets 必须更清楚地说明它如何实现所需的输出。这是代码-
# Arrange groups of d number of elements from the input array into
# rows of a 2D array and pad with k*d zeros in each row.
# Thus, the shape of this 2D array would be (k,d+k*d)
A_zeroappend = np.zeros((k,(k+1)*d))
A_zeroappend[:,:d] = A.reshape(-1,d)
# Get rid of the last row of appended zeros.
# Reshape and transpose to desired output shape (k*d,k)
out = A_zeroappend.ravel()[:k*k*d].reshape(-1,k*d).T
运行时测试
这是一个快速运行时测试,比较了建议的方法和other answer 中列出的基于np.repeat 的方法-
In [292]: k = 800
...: d = 800
...: A = np.random.randint(2,9,(1,k*d))
...:
In [293]: %%timeit
...: B = np.zeros((k*d,k))
...: B[np.arange(k*d),np.arange(k).repeat(d)]=A
...:
1 loops, best of 3: 342 ms per loop
In [294]: %%timeit
...: A_zeroappend = np.zeros((k,(k+1)*d))
...: A_zeroappend[:,:d] = A.reshape(-1,d)
...: out = A_zeroappend.ravel()[:k*k*d].reshape(-1,k*d).T
...:
100 loops, best of 3: 3.07 ms per loop
似乎提议的方法快得惊人!