Why does the measurement order change with Boolean indexing?

When we have M forms (a, b, c) and an index array v , which we use to index the last array, why M[i, :, v] leads to an array of form (d, b) (with d number of true values in v )? As below:

 In [409]: M = zeros((100, 20, 40)) In [410]: val = ones(shape=(40,), dtype="bool") In [411]: M[0, :, :].shape Out[411]: (20, 40) # As expected In [412]: M[0, :, val].shape Out[412]: (40, 20) # Huh? Why (40, 20), not (20, 40)? In [413]: M[:, :, val].shape Out[413]: (100, 20, 40) # s expected again 

Why does M[0, :, val] have the form (40, 20) and not (20, 40) ?

+2
source share
1 answer

According to the boolean indexing section of the docs http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing

The combination of several Boolean indexing arrays or logical arrays with a whole indexing array is best understood using the analogy of obj.nonzero ().

 ind = np.nonzero(val)[0] # array([ 0, 1, 2, ...., 39], dtype=int32) M[0, :, ind].shape # (40,20) 

So, let's move on to the section on combining advanced and basic indexing http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

This is a case of the form: x[arr1, :, arr2]

in the first case, the dimensions resulting from the extended indexing operation first appear in the result array, and after that the subspace values.

So, part 0 and ind creates a selection (40,) , a : in the middle creates a (20,) . Putting the last part : resulting size is (40,20) . This is mainly due to the ambiguity in this indexing style, so it sequentially selects the portion of the slice at the end.

The way to select these values ​​and save the desired shape (more or less) is to use np.ix_ to generate a tuple of indices.

 M[np.ix_([0],np.arange(20),ind)].shape # (1, 20, 40) 

You can use np.squeeze to remove the initial dimension 1 .

This use of ix_ illustrated at the end of the "purely index array indexing" section http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing

+3
source

All Articles