Using the numpy function numpy.nonzero
, is there an elegant way to check if the tuples as output are empty arrays?
In MATLAB, this is very easy
i.e.
answer = find( matrix_a < matrix_b );
isempty(answer)
Using the numpy function numpy.nonzero
, is there an elegant way to check if the tuples as output are empty arrays?
In MATLAB, this is very easy
i.e.
answer = find( matrix_a < matrix_b );
isempty(answer)
The numpythonic way of doing this is to use any
/all
methods on the ndarray objects directly.
In your example case, your code is asking: Are there no indices where matrix_a is less than matrix_b?
not (matrix_a < matrix_b).any()
Equivalently, does matrix_a have all elements greater than the corresponding elements in matrix_b?
(matrix_a >= matrix_b).all()
For a
(10,10) range(100)
In [201]: np.nonzero(a>100)
Out[201]: (array([], dtype=int32), array([], dtype=int32))
nonzero
returns a tuple, with an array for each dimension. This tuple can be used to index all the elements where the condition is true.
So you could test for 'empty' nonzero
by looking at the length of one of those arrays.
len(np.nonzero(a>98)[0])==0
any
on the boolean mask appears simpler, though in quick tests, it is actually slower.
np.any(a>98)
The MATLAB 'find' returns the items that match. The numpy equivalent is a[np.nonzero(a>100)]
, or using the boolean mask directly a[a>100]
.
So my new nomination for a fast isempty(find...))
look alike is len(a[...])==0
.