Let's say I've got a matrix like this:
mat1 = np.array([1,0,1], [1,1,0], [0,0,0]);
And I've got another one like this:
mat2 = np.array([0,1,0], [0,0,1], [1,1,1]);
I want to detect if something like
np.add(mat1, mat2);
has only 1's or 0's, namely some 1's and some 0's, all 0's, or all 1's.
n.b. - Comment your code.
You can use
unique
You can also use
setdiff1d
How about this:
Simply:
Use
numpy.all
,numpy.any
:np.all(mat == 0)
np.all(mat == 1)
np.any(mat == 0)
np.any(mat == 1)
UPDATE
To check whether the array contains only
1
or0
, nothing else, use following:Check this out:
np.sum(np.unique(mat0.ravel()))
So,
mat0.ravel()
does this:This new object is an array, namely the
[1,0,0,0,0,0,1,1,0]
object above. Now,np.unique(mat0.ravel())
finds all the unique elements and sorts them and puts them in a set, like this:From here if one applies
np.sum
on this, namelynp.sum(np.unique(mat0.ravel()))
we get the sum of the contents of the set, so a good condition to check if only a0
or1
in each and every cell in matrix is the following:n.b. - This is only for non-negative integers.
If you know it's int dtype, then (suprisingly) it's faster to check the max and min (even without doing these operations simultaneously):