Numpy教程-布尔索引 [英] Numpy tutorial - Boolean indexing
本文介绍了Numpy教程-布尔索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
阅读Numpy快速教程,我听不懂这句话.
Reading Numpy quick tutorial, I cannot understand this sentence.
a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True])
b2 = np.array([True,False,True,False])
>>> a[b1,b2]
array([ 4, 10])
为什么a[b1,b2]
是array([4,10])
而不是array([[4,6],[8,10]])
?
推荐答案
It's because you are performing integer array indexing
there.
在内部,从布尔数组中计算索引-
Internally, the indices are computed from the boolean arrays -
In [72]: idx1 = np.flatnonzero(b1)
In [73]: idx2 = np.flatnonzero(b2)
In [75]: idx1
Out[75]: array([1, 2])
In [76]: idx2
Out[76]: array([0, 2])
然后,使用索引数组中的每个元素对每组索引执行整数数组索引-
Then, the integer array indexing is performed on each group of indices using each element from the indexing arrays -
In [77]: a[1,0] # 1 from idx1[0], 0 from idx2[0]
Out[77]: 4
In [78]: a[2,2] # 2 from idx1[1], 2 from idx2[1]
Out[78]: 10
要实现MATLAB样式的块提取,我们需要使用开放数组,并在每个轴/维度中建立索引.要在NumPy中创建此类开放数组,我们需要 np.ix_
-
To achieve that MATLAB styled block extraction, we need to use open arrays and index into each of those axes/dims. To create such open arrays in NumPy, we have np.ix_
-
In [89]: np.ix_(b1,b2)
Out[89]:
(array([[1],
[2]]), array([[0, 2]]))
In [90]: a[np.ix_(b1,b2)]
Out[90]:
array([[ 4, 6],
[ 8, 10]])
这篇关于Numpy教程-布尔索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文