Skip to content Skip to sidebar Skip to footer

Why Does Boolean Indexing Of A 2d Numpy Array Produces 1d Array?

I was experimenting with boolean indexing in NumPy and came across this which is confusing me: import numpy as np np.random.seed(0) Created a 7 x 4 array: data = np.random.rand(

Solution 1:

Numpy has no a-priori way of knowing where the True elements of your mask will be. It is purely happenstance that your selection is aligned so neatly in columns.

To understand why the result is raveled into a 1D array, imagine how to handle the case where you have two selections in each row, but not always from the same column. Now imagine a case where the number of selections in each row is different, possibly with some rows completely empty. Numpy has to be able to handle all these cases consistently. It would be much slower and would cause a lot of problems to return an array of different shape depending on the contents of your mask.

To make the selection of the columns you want, use the appropriate index:

a[:, ::3]

OR

a[:, [0, 3]]

Post a Comment for "Why Does Boolean Indexing Of A 2d Numpy Array Produces 1d Array?"