[英]how to slice a 2d array based on indices given in another 2d array
I have an MxN
array called A
which stores the data I want.我有一个名为
A
的MxN
数组,它存储我想要的数据。 I have another M x N2
array B
which stores array indices, and N2<N
.我有另一个存储数组索引的
M x N2
数组B
和N2<N
。 Each row of B
stores the indices of the elements I want to get from A for that row. B
的每一行都存储了我想从 A 获取该行的元素的索引。 For example, the following code works for me:例如,以下代码适用于我:
A_reduced = np.zeros((M,N2))
for i in range(M):
A_reduced[i,:] = A[i,B[i,:]]
Are there any 'vectorized' ways to extract the desired elements from A
based on B
instead of looping through each row?是否有任何“矢量化”方法可以根据
B
从A
中提取所需元素,而不是遍历每一行?
You can exploit array indexing and use reshape:您可以利用数组索引并使用 reshape:
# set up M=N=4, N2=2
a = np.arange(16).reshape(4,4)
b = np.array([[1,2],[0,1],[2,3],[1,3]])
row_idx = np.repeat(np.arange(b.shape[0]),b.shape[1])
col_idx = b.ravel()
# output:
a[row_idx, col_idx].reshape(b.shape)
Output: Output:
array([[ 1, 2],
[ 4, 5],
[10, 11],
[13, 15]])
Update : Another similar solution更新:另一个类似的解决方案
row_idx = np.repeat(np.arange(b.shape[0]),b.shape[1]).reshape(b.shape)
# output
a[row_idx,b]
In [203]: A = np.arange(12).reshape(3,4)
In [204]: B = np.array([[0,2],[1,3],[3,0]])
Your row iteration:您的行迭代:
In [207]: A_reduced = np.zeros((3,2),int)
In [208]: for i in range(3):
...: A_reduced[i,:] = A[i, B[i,:]]
...:
In [209]: A_reduced
Out[209]:
array([[ 0, 2],
[ 5, 7],
[11, 8]])
A 'vectorized' version: “矢量化”版本:
In [210]: A[np.arange(3)[:,None], B]
Out[210]:
array([[ 0, 2],
[ 5, 7],
[11, 8]])
and streamlined with a newish function:并使用新的 function 进行简化:
In [212]: np.take_along_axis(A,B,axis=1)
Out[212]:
array([[ 0, 2],
[ 5, 7],
[11, 8]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.