I have a large
Here's one way. I assume numpy has been imported using
import numpy as np.
In : a Out: array([[0, 1, 0], [1, 0, 1], [0, 0, 0], [1, 1, 0], [0, 0, 0]]) In : np.where(~a.any(axis=1)) Out: array([2, 4])
It's a slight variation of this answer: How to check that a matrix contains a zero column?
Here's what's going on:
any method returns True if any value in the array is "truthy". Nonzero numbers are considered True, and 0 is considered False. By using the argument
axis=1, the method is applied to each row. For the example
a, we have:
In : a.any(axis=1) Out: array([ True, True, False, True, False], dtype=bool)
So each value indicates whether the corresponding row contains a nonzero value. The
~ operator is the binary "not" or complement:
In : ~a.any(axis=1) Out: array([False, False, True, False, True], dtype=bool)
(An alternative expression that gives the same result is
(a == 0).all(axis=1).)
To get the row indices, we use the
where function. It returns the indices where its argument is True:
In : np.where(~a.any(axis=1)) Out: (array([2, 4]),)
where returned a tuple containing a single array.
where works for n-dimensional arrays, so it always returns a tuple. We want the single array in that tuple.
In : np.where(~a.any(axis=1)) Out: array([2, 4])