Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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.

like image 572
user7289 Avatar asked Dec 04 '13 10:12

user7289


People also ask

How do you create a boolean matrix in NumPy?

A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.

How do you make a boolean matrix in Python?

A boolean array can be made using dtype=bool, manually. All values other than '0', 'False', 'None', or empty strings are considered True in a boolean array.

Does NumPy arrays support boolean indexing?

We can also index NumPy arrays using a NumPy array of boolean values on one axis to specify the indices that we want to access. This will create a NumPy array of size 3x4 (3 rows and 4 columns) with values from 0 to 11 (value 12 not included).


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

like image 169
user2357112 supports Monica Avatar answered Oct 17 '22 08:10

user2357112 supports Monica


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

like image 24
seberg Avatar answered Oct 17 '22 07:10

seberg