How to 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?


numpy.array(old_matrix, dtype=bool)


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.