How do I convert a numpy matrix into a boolean matrix?
numpy.array(old_matrix, dtype=bool)
Alternatively,
old_matrix != 0
The first version is an elementwise coercion to boolean. Analogous constructs will work for conversion to other data types. The second version is an elementwise comparison to 0. It involves less typing, but ran slightly slower when I timed it. Which you use is up to you; I'd probably decide based on whether "convert to boolean" or "compare to 0" is a better conceptual description of what I'm after.
Simply use equality check:
Suppose a is your numpy matrix, use b = (a == 0) or b = (a != 0) to get the boolean value matrix.
In some case, since the value maybe sufficiently small but non-zero, you may use abs(a) < TH, where TH is the numerical threshold you set.
You should use array.astype(bool)
(or array.astype(dtype=bool)
). Works with matrices too.
.astype(dtype)
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.astype.html
It's nice that this will work on binary-like floats including 0.
and 1.
.
old_matrix.astype(bool)