当你用多个数组索引一个数组时,它会用索引数组中的元素对来索引
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> b1
array([False, True, True], dtype=bool)
>>> b2
array([ True, False, True, False], dtype=bool)
>>> a[b1, b2]
array([ 4, 10])
注意这相当于:
>>> a[(1, 2), (0, 2)]
array([ 4, 10])
a[1, 0] 和 a[2, 2] 的元素
>>> a[1, 0]
4
>>> a[2, 2]
10
由于这种成对行为,您通常不能使用单独的长度数组进行索引(它们必须能够广播)。所以这个例子有点意外,因为两个索引数组都有两个索引,它们是True;例如,如果一个有三个 True 值,你会得到一个错误:
>>> b3 = np.array([True, True, True, False])
>>> a[b1, b3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (3,)
所以这特别是让您知道索引数组必须能够一起广播(以便它可以以一种智能的方式将索引组合在一起;例如,如果一个索引数组只有一个值,那将被重复与另一个索引数组中的每个值)。
要获得您期望的结果,您可以单独索引结果:
>>> a[b1][:, b2]
array([[ 4, 6],
[ 8, 10]])
否则,您也可以将索引数组转换为与a 形状相同的二维数组,但请注意,如果这样做,结果将是一个线性数组(因为可以拉出任意数量的元素,当然可能不是方形的):
>>> a[np.outer(b1, b2)]
array([ 4, 6, 8, 10])