從2D數組中提取元素,使用索引從另一個數組
Problem:
Consider two NumPy arrays:
A = np.array([[0, 1], [2, 3], [4, 5]]) B = np.array([[1], [0], [1]]) # Index arrayThe goal is to extract one element from each row of A, where the specific element is specified by the index in the corresponding row of B. The expected output should be:
C = np.array([[1], [2], [5]])
a [np.arange(a.shape [0]),b.ravel()]A = np.array([[0, 1], [2, 3], [4, 5]]) B = np.array([[1], [0], [1]]) # Index arraynp.Choose(b.ravel(),a.t),a.t)
在這種替代方法中,您將A型A型A匹配B的形狀,然後使用NP.Choose使用NP.Choose來選擇基於Flatteed Barteed b的blattened Baray。 Itable解開包裝(python> = 3.6):
[i] for b.ravel())C = np.array([[1], [2], [5]])[a [i] [j]為i,j In zip(range(a.shape [0]),b.ravel(a.shape [0]),b.ravel())]
[np.stack([range(a.shape [0]),b.ravel()],axis = 1)]在這種情況下,它將創建一個帶有行索引和B索引的2D數組,可用於從a中選擇所需的元素。 最合適的解決方案取決於任務的特定要求和約束,例如效率,可讀性,以及與Numpy的較舊版本的合適性。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3