How to convert a boolean array to an int array How to convert a boolean array to an int array python python

How to convert a boolean array to an int array


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:

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


The 1*y method works in Numpy too:

>>> import numpy as np>>> x = np.array([4, 3, 2, 1])>>> y = 2 >= x>>> yarray([False, False,  True,  True], dtype=bool)>>> 1*y                      # Method 1array([0, 0, 1, 1])>>> y.astype(int)            # Method 2array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]>>> map(lambda x: 1 if x else 0, testList)[0, 0, 1, 1]>>> map(int, testList)[0, 0, 1, 1]

Or using list comprehensions:

>>> testList[False, False, True, True]>>> [int(elem) for elem in testList][0, 0, 1, 1]


Using numpy, you can do:

y = x.astype(int)

If you were using a non-numpy array, you could use a list comprehension:

y = [int(val) for val in x]