numpy阵列整数在多个维度中索引



我敢肯定,我缺少整数索引的东西,并且可以使用一些帮助。说我创建了一个2D数组:

>>> import numpy as np
>>> x=np.array(range(24)).reshape((4,6))
>>> x
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

我可以选择:

选择第1和2
>>> x[[1,2],:]
array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])

或第2行和第3列的第1列,

>>> x[[1,2],1]
array([ 7, 13])

因此,我可以选择以下第1行的第3、4和5列是有意义的:

>>> x[[1,2],[3,4,5]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape

,我需要以两个步骤进行操作:

>>> a=x[[1,2],:]
>>> a
array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17]])
>>> a[:,[3,4,5]]
array([[ 9, 10, 11],
       [15, 16, 17]])

来自R,我的期望似乎是错误的。您能确认这确实是不可能的,还是建议更好的选择?谢谢!

编辑:请注意,在示例中,我选择的行和列是连续的,但不必是。换句话说,切片索引对我的案件无能为力。

您还可以选择在索引阵列中使用广播,这是我通常会做的,而不是索引两次,这会创建数据的中间副本:

>>> x[[[1], [2]],[[3, 4, 5]]]
array([[ 9, 10, 11],
       [15, 16, 17]])

看到正在发生的事情以及如何处理大量索引:

>>> row_idx = np.array([1, 2])
>>> col_idx = np.array([3, 4, 5])
>>> x[row_idx.reshape(-1, 1), col_idx]
array([[ 9, 10, 11],
       [15, 16, 17]])

类似的东西:

In [28]: x[1:3, 3:6]                                                                             
Out[28]: 
array([[ 9, 10, 11],
       [15, 16, 17]])

最新更新