對于我的測驗用例,我有一個 32 行和 5 列的陣列。
test = np.arange(0,160).reshape(32,-1, order='F')
print(test)
[[ 0 32 64 96 128]
[ 1 33 65 97 129]
[ 2 34 66 98 130]
[ 3 35 67 99 131]
[ 4 36 68 100 132]
[ 5 37 69 101 133] ... and so on
在我的情況下,列是時間序列,行表示記錄位置。我現在想將記錄位置重新排列到它們的真實位置(idxs 是這個映射),而是將時間序列擴展到第三維。
idxs = np.array([[ 0, 7, 8, 15, 16, 23, 24, 31],
[ 1, 6, 9, 14, 17, 22, 25, 30],
[ 2, 5, 10, 12, 18, 21, 26, 29],
[ 3, 4, 11, 12, 19, 20, 27, 28]])
所需輸出:測驗中每一列的形狀 (4,8) 陣列,按照 idxs 中的映射排列,沿軸 2 堆疊以獲得:
after_reshape.shape == (4,8,5) #for this testcase only 5
timepoints/columns
print(after_reshape[:,:,0])
[[ 0 7 8 15 16 23 24 31]
[ 1 6 9 14 17 22 25 30]
[ 2 5 10 12 18 21 26 29]
[ 3 4 11 12 19 20 27 28]]
print(after_reshape[:,:,1])
[[32 39 40 47 48 55 56 63]
[33 38 41 46 49 54 57 62]
[34 37 42 44 50 53 58 61]
[35 36 43 44 51 52 59 60]]
如果我使用 for 回圈,我可以重復test[:,i][idxs]獲取 (4,8) 陣列,但仍需要堆疊它們。我假設也有一個不回圈的選項?
uj5u.com熱心網友回復:
這應該有效:
test = np.arange(0,160).reshape(32,-1, order='F')
idxs = np.array([[ 0, 7, 8, 15, 16, 23, 24, 31],
[ 1, 6, 9, 14, 17, 22, 25, 30],
[ 2, 5, 10, 12, 18, 21, 26, 29],
[ 3, 4, 11, 12, 19, 20, 27, 28]])
after_reshape = test[idxs.flatten()].reshape([4, 8, -1])
然后after_reshape[:, :, 0]給你:
array([[ 0, 7, 8, 15, 16, 23, 24, 31],
[ 1, 6, 9, 14, 17, 22, 25, 30],
[ 2, 5, 10, 12, 18, 21, 26, 29],
[ 3, 4, 11, 12, 19, 20, 27, 28]])
和after_reshape[:, :, 1]:
array([[32, 39, 40, 47, 48, 55, 56, 63],
[33, 38, 41, 46, 49, 54, 57, 62],
[34, 37, 42, 44, 50, 53, 58, 61],
[35, 36, 43, 44, 51, 52, 59, 60]])
按照要求
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436814.html
上一篇:遍歷遞回陣列并更新
