1

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also just use (a != row).any(axis=1) directly in most cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.