4

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

1 Answer 1

5

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

@JeongYeojin If this solved your question, consider accepting it by clicking on the hollow tick next to the solution, More info here - meta.stackexchange.com/questions/5234/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.