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]
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
source share