33

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.

1
  • Do the zero values need to be set to false? Or is there another condition? Commented Dec 4, 2013 at 10:44

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

22

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

Comments

5

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.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.