riv
riv

Reputation: 7343

Numpy filter 2D array by two masks

I have a 2D array and two masks, one for columns, and one for rows. If I try to simply do data[row_mask,col_mask], I get an error saying shape mismatch: indexing arrays could not be broadcast together with shapes .... On the other hand, data[row_mask][:,col_mask] works, but is not as pretty. Why does it expect indexing arrays to be of the same shape?

Here's a specific example:

import numpy as np
data = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
row_mask = np.array([True, True, False, True])
col_mask = np.array([True, True, False])
print(data[row_mask][:,col_mask]) # works
print(data[row_mask,col_mask]) # error

Upvotes: 2

Views: 1888

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

Use ix_ function :

>>> data[np.ix_(row_mask,col_mask)]
array([[ 1,  2],
       [ 4,  5],
       [10, 11]])

Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the obj.nonzero() analogy. The function ix_ also supports boolean arrays and will work without any surprises.

Upvotes: 3

Related Questions