问题描述
我有一个多维数组numpy的:
I have a multidimensional NumPy array:
In [1]: m = np.arange(1,26).reshape((5,5))
In [2]: m
Out[2]:
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]])
和另一个阵列 P = np.asarray([1,1],[3,3]])
。我想 P
作为指标为 M
A阵列,即:
and another array p = np.asarray([[1,1],[3,3]])
. I wanted p
to act as a array of indexes for m
, i.e.:
m[p]
array([7, 19])
不过,我得到:
In [4]: m[p]
Out[4]:
array([[[ 6, 7, 8, 9, 10],
[ 6, 7, 8, 9, 10]],
[[16, 17, 18, 19, 20],
[16, 17, 18, 19, 20]]])
我怎样才能得到所期望的片 M
使用 P
?
推荐答案
numpy的是使用阵列只在第一个维度索引。一般来说,对于一个多维数组的下标应该是一个元组。这将接近你想要的东西一点点让你:
Numpy is using your array to index the first dimension only. As a general rule, indices for a multidimensional array should be in a tuple. This will get you a little closer to what you want:
>>> m[tuple(p)]
array([9, 9])
但是,现在你与1两次索引第一尺寸,并用3.索引与1和3,然后在第二带1和3还第一维的第二两次,可以转置的数组:
But now you are indexing the first dimension twice with 1, and the second twice with 3. To index the first dimension with a 1 and a 3, and then the second with a 1 and a 3 also, you could transpose your array:
>>> m[tuple(p.T)]
array([ 7, 19])
这篇关于索引多维数组使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!