給定一個 3D 陣列:
a = np.arange(3*4*5).reshape(3,4,5)
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, 36, 37, 38, 39]],
[[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
我想創建以下矩陣:
result =
array([[20, 21, 22, 23, 24],
[ 5, 6, 7, 8, 9],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]])
使用索引idx = [1,0,2,2]
即,我想“取”每個矩陣,從維度 1中指定的行idx、位置len(idx)==a.shape[1]和np.max(idx)<a.shape[0]idx 。choose
uj5u.com熱心網友回復:
鑒于您的陣列具有三個維度(x,y,z),因為您想為 yth 方向上的每一行取一個值,您可以這樣做:
a[idx, range(a.shape[1])]
輸出:
array([[20, 21, 22, 23, 24],
[ 5, 6, 7, 8, 9],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488932.html
