我有一個 3D 陣列,可以解釋為位置的 2D 矩陣,其中每個位置都是坐標的 2D 陣列[x,y]。
然后我有一個二維索引串列,每個索引都以 [行,列] 表示矩陣中的一個位置。我想從與所有這些索引對應的矩陣中獲取位置。
我正在做的是:
import numpy as np
input_matrix = np.array(
[[[0.0, 1.5], [3.0, 3.0]], [[7.0, 5.2], [6.0, 7.0]]]
)
indices = np.array([[1, 0], [1, 1]])
selected_elements = np.array([input_matrix[tuple(idx)] for idx in indices])
因此,例如,對應于 2D 索引的 2D 元素[1, 0]將是[7.0, 5.2]等等。
我的代碼有效,但我想知道是否有更好的方法,例如完全使用 numpy(例如,在多個 2D 索引的情況下不必使用串列理解)。
我嘗試使用 numpy take,但它似乎沒有產生想要的結果。
uj5u.com熱心網友回復:
您可以使用:
input_matrix[tuple(indices.T)]
或者,正如評論中所建議的:
input_matrix[indices[:,0], indices[:,1]]
輸出:
array([[7. , 5.2],
[6. , 7. ]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/519661.html
標籤:麻木的numpy索引
上一篇:使用numpy內核并在從python呼叫的C函式中的矩陣上填充的邊界問題
下一篇:如何將矩陣轉換為向量?
