下面是基於零填充到所述輸入陣列的有效方法。每個代碼步驟中的內聯註釋必須使其更清楚地說明如何實現所需的輸出。下面的代碼 -
# 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
好像所提出的方法太快了!
這就是完美!多謝,夥計 – farhawa