user7289
user7289

Reputation: 34318

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

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.

Upvotes: 32

Views: 71903

Answers (4)

Kermit
Kermit

Reputation: 5982

.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)

Upvotes: 5

seberg
seberg

Reputation: 8975

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

Upvotes: 21

user2357112
user2357112

Reputation: 280227

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.

Upvotes: 47

Ray
Ray

Reputation: 2510

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.

Upvotes: 5

Related Questions