我有一個形狀(n,x,y)的多維陣列。對于這個例子可以使用這個陣列
A = array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]],
[[24, 25, 26],
[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]])
然后我有另一個多維陣列,它具有我想在原始陣列 A 上使用的索引值。它具??有形狀 (z,2) 并且這些值表示行值索引的
Row_values = array([[0,1],
[0,2],
[1,2],
[1,3]])
所以我想使用 row_values 中的所有索引值來應用于 A 中的三個陣列中的每一個,所以我最終得到一個形狀為 (12,2,3) 的最終陣列
Result = ([[[0,1,2],
[3,4,5]],
[[0,1,2],
[6,7,8]],
[[3,4,5],
[6,7,8]]
[[3,4,5],
[9,10,11],
[[12,13,14],
[15,16,17]],
[[12,13,14],
[18,19,20]],
[[15,16,17],
[18,19,20]],
[[15,16,17],
[21,22,23]],
[[24,25,26],
[27,28,29]],
[[24,25,26],
[30,31,32]],
[[27,28,29],
[30,31,32]],
[[27,28,29],
[33,34,35]]]
我曾嘗試使用 np.take() 但未能使其正常作業。不確定是否有另一個更容易使用的 numpy 函式
uj5u.com熱心網友回復:
我們可以利用NumPy的先進的索引和使用np.repeat,并np.tile與它一起。
cidx = np.tile(Row_values, (A.shape[0], 1))
ridx = np.repeat(np.arange(A.shape[0]), Row_values.shape[0])
out = A[ridx[:, None], cidx]
# out.shape -> (12, 2, 3)
輸出:
array([[[ 0, 1, 2],
[ 3, 4, 5]],
[[ 0, 1, 2],
[ 6, 7, 8]],
[[ 3, 4, 5],
[ 6, 7, 8]],
[[ 3, 4, 5],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17]],
[[12, 13, 14],
[18, 19, 20]],
[[15, 16, 17],
[18, 19, 20]],
[[15, 16, 17],
[21, 22, 23]],
[[24, 25, 26],
[27, 28, 29]],
[[24, 25, 26],
[30, 31, 32]],
[[27, 28, 29],
[30, 31, 32]],
[[27, 28, 29],
[33, 34, 35]]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346094.html
