Reputation:
How can I filter elements of an NxM
matrix in scipy/numpy
in Python by some condition on the rows?
For example, just you can do where(my_matrix != 3
) which treats the matrix "element-wise", I want to do this by row, so that you can ask things like where (my_matrix != some_other_row)
, to filter out all rows that are not equal to some_other_row
. How can this be done?
Upvotes: 1
Views: 2568
Reputation: 601371
Assume you have a matrix
a = numpy.array([[0, 1, 2],
[3, 4, 5],
[0, 1, 2]])
and you want to get the indices of the rows tha are not equal to
row = numpy.array([0, 1, 2])
You can get these indices by
indices, = (a != row).any(1).nonzero()
a != row
compares each row of a
to row
element-wise, returning a Boolean array of the same shape as a
. Then, we use any()
along the first axis to find rows in which any element differs from the corresponding element in row
. Last, nonzero()
gives us the indices of those rows.
Upvotes: 3