+4 votes
in Programming Languages by (74.2k points)
How can I convert a Numpy matrix of cell values True and False to 1 and 0? I do not want to use "for" loop for this task as it will be time-consuming.

E.g.

array([[ True, False, False],
       [False, False,  True]])

to

array([[1, 0, 0],
       [0, 0, 1]])

1 Answer

+1 vote
by (351k points)
selected by
 
Best answer

You can use one of the following two approaches to convert True/False to 1/0.

1. Using astype(int)

>>> import numpy as np
>>> a=np.array([[True, False, False],[False,False,True]])
>>> a
array([[ True, False, False],
       [False, False,  True]])
>>> a.astype(int)
array([[1, 0, 0],
       [0, 0, 1]])

2. Simply multiply your matrix by 1:

>>> import numpy as np
>>> a=np.array([[True, False, False],[False,False,True]])
>>> a
array([[ True, False, False],
       [False, False,  True]])
>>> a*1
array([[1, 0, 0],
       [0, 0, 1]])


...