从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