numpy:使用2D索引数组进行2D数组访问 [英] Numpy: 2D array access with 2D array of indices
问题描述
我有两个数组,一个是索引对的矩阵,
I have two arrays, one is a matrix of index pairs,
a = array([[[0,0],[1,1]],[[2,0],[2,1]]], dtype=int)
和另一个是要在这些索引处访问的数据矩阵
and another which is a matrix of data to access at these indices
b = array([[1,2,3],[4,5,6],[7,8,9]])
,并且我希望能够使用a的索引来获取b
的条目.只是在做:
and I want to able to use the indices of a to get the entries of b
. Just doing:
>>> b[a]
不起作用,因为它为a
中的每个条目给出了一行b,即
does not work, as it gives one row of b for each entry in a
, i.e.
array([[[[1,2,3],
[1,2,3]],
[[4,5,6],
[4,5,6]]],
[[[7,8,9],
[1,2,3]],
[[7,8,9],
[4,5,6]]]])
当我想使用a
的最后一个轴上的索引对给出b
的两个索引时:
when I would like to use the index pair in the last axis of a
to give the two indices of b
:
array([[1,5],[7,8]])
是否有一种干净的方法?还是需要重塑b
的形状并以相应的方式组合a
的列?
Is there a clean way of doing this, or do I need to reshape b
and combine the columns of a
in a corresponding manner?
在我的实际问题中,a
大约有500万个条目,而b
是100 x 100,我想避免for循环.
In my actual problem a
has about 5 million entries, and b
is 100-by-100, I'd like to avoid for loops.
推荐答案
实际上,这可行:
b[a[:, :, 0],a[:, :, 1]]
给予array([[1, 5],
[7, 8]])
.
Gives array([[1, 5],
[7, 8]])
.
这篇关于numpy:使用2D索引数组进行2D数组访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!