Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

python - Numpy tutorial - Boolean indexing

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])

Why a[b1,b2] is array([4,10]) instead of array([[4,6],[8,10]])?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...