Kwolf Kwolf - 2 months ago 13
Python Question

How to convert a boolean array to an int array

I use Scilab, and want to convert an array of booleans into an array of integers:

>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False, True, True], dtype=bool)


In Scilab I can use:

>>> bool2s(y)
0. 0. 1. 1.


or even just multiply it by 1:

>>> 1*y
0. 0. 1. 1.


Is there a simple command for this in Python, or would I have to use a loop?

Answer

Numpy arrays have an astype method. Just do y.astype(int).

Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:

>>> x
array([ True, False,  True], dtype=bool)
>>> x + [1, 2, 3]
array([2, 2, 4])
Comments