How do I convert a numpy matrix into a boolean matrix?

Viewed 38643

I have a n x n matrix in numpy which has 0 and non-0 values. Is there a way to easily convert it to a boolean matrix?

Thanks.

4 Answers
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.

You should use array.astype(bool) (or array.astype(dtype=bool)). Works with matrices too.

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.

Related