Anindya Dutta
Anindya Dutta

Reputation: 1982

Filter arrays in Numpy

I have an array: [[True], [False], [True]]. If I would want this array to filter my existing array, e.g [[1,2],[3,4],[5,6]] should get filtered to [[1,2],[5,6]], what is the correct way to do this?

A simple a[b] indexing gives the error: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1

Upvotes: 1

Views: 93

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20434

Use .ravel...

From the documentation, ravel will:

Return a contiguous flattened array.

So if we have your b array:

b = np.array([[True], [False], [True]])

we can take the boolean values out of their sub-arrays with:

b.ravel()

which gives:

array([ True, False,  True], dtype=bool)

So then, we can simply use b.ravel() as a mask for a and it will work as you want:

a = np.array([[1,2], [3,4], [5,6]])
b = np.array([[True], [False], [True]])

c = a[b.ravel()]

which gives c as:

array([[1, 2],
       [5, 6]])

Upvotes: 1

user6655984
user6655984

Reputation:

The solution is to get the array [[True], [False], [True]] into shape [True, False, True], so that it works for indexing the rows of the other array. As Divakar said, ravel does this; in general it flattens any array to a 1D array. Another option is squeeze which removes the dimensions with size 1 but leaves the other dimensions as they were,

Upvotes: 1

Related Questions