How Does One Test If A Matrix In Python Has Only 1's And 0's?
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 detec
Solution 1:
- all 0:
np.all(mat == 0)
- all 1:
np.all(mat == 1)
- some 0:
np.any(mat == 0)
- some 1:
np.any(mat == 1)
>>> mat1 = np.array([[1,0,1], [1,1,0], [0,0,0]])
>>> mat2 = np.array([[0,1,0], [0,0,1], [1,1,1]])
>>> np.all(mat1 == 0)
False
>>> np.any(mat1 == 0)
True
>>> np.all(mat1 == 1)
False
>>> np.any(mat1 == 1)
True
>>> mat3 = mat1 + mat2
>>> mat3
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
>>> np.all(mat3 == 1)
True
UPDATE
To check whether the array contains only 1
or 0
, nothing else, use following:
>>> mat1 = np.array([[1,0,1], [1,1,0], [0,0,0]])
>>> mat2 = np.array([[0,1,2], [3,4,5], [6,7,8]])
>>> np.all((mat1 == 0) | (mat1 == 1))
True
>>> np.all((mat2 == 0) | (mat2 == 1))
False
Solution 2:
How about this:
>>> def check(matrix):
... # flatten up the matrix into one single list
... # and set on the list it should be [0,1] if it
... # contains only 0 and 1. Then do sum on that will
... # return 1
... if sum(set(sum(matrix,[]))) > 1:
... return False
... return True
...
>>>
>>> check([[1,0,1], [1,1,0], [0,0,0]])
True
>>> check([[1,0,1], [1,1,0], [0,0,2]])
False
>>> check([[1,0,1], [1,1,0], [0,0,3]])
False
>>>
Solution 3:
Simply:
In [6]:
set((mat1+mat2).ravel()).issubset(set((1,0)))
Out[6]:
True
In [7]:
mat3 = np.array([[0,5,0], [0,0,1], [1,1,1]])
set((mat1+mat3).ravel()).issubset(set((1,0)))
Out[7]:
False
Solution 4:
If you know it's int dtype, then (suprisingly) it's faster to check the max and min (even without doing these operations simultaneously):
In [11]: m = np.random.randint(0, 2, (10, 10))
In [12]: %timeit np.all((m == 0) | (m == 1))
10000 loops, best of 3: 33.7 µs per loop
In [13]: %timeit m.dtype == int and m.min() == 0 and m.max() == 1
10000 loops, best of 3: 29.8 µs per loop
In [21]: m = np.random.randint(0, 2, (10000, 10000))
In [22]: %timeit np.all((m == 0) | (m == 1))
1 loops, best of 3: 705 ms per loop
In [23]: %timeit m.dtype == int and m.min() == 0 and m.max() == 1
1 loops, best of 3: 481 ms per loop
Solution 5:
You can use unique
import numpy as np
mat1 = np.array([[1,0,1], [1,1,0], [0,0,0]])
np.unique(mat1)
# array([0, 1])
1 in np.unique(mat1)
# True
0 in np.unique(mat1)
# True
np.unique(mat1) == [0, 1]
# array([ True, True], dtype=bool)
You can also use setdiff1d
np.setdiff1d(mat1, [0, 1])
# array([], dtype=int64)
np.setdiff1d(mat1, [0, 1]).size
# 0
Post a Comment for "How Does One Test If A Matrix In Python Has Only 1's And 0's?"