How to convert a boolean array to an int array
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow
--
Chapters
00:00 How To Convert A Boolean Array To An Int Array
00:31 Accepted Answer Score 243
00:54 Answer 2 Score 78
01:21 Answer 3 Score 37
01:35 Answer 4 Score 20
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/1750...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #integer #boolean #typeconversion #scilab
#avk47
    Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow
--
Chapters
00:00 How To Convert A Boolean Array To An Int Array
00:31 Accepted Answer Score 243
00:54 Answer 2 Score 78
01:21 Answer 3 Score 37
01:35 Answer 4 Score 20
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/1750...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #integer #boolean #typeconversion #scilab
#avk47
ACCEPTED ANSWER
Score 243
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])
ANSWER 2
Score 78
The 1*y method works in Numpy too:
>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([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]
ANSWER 3
Score 37
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]
ANSWER 4
Score 20
Most of the time you don't need conversion:
>>>array([True,True,False,False]) + array([1,2,3,4])
array([2, 3, 3, 4])
The right way to do it is:
yourArray.astype(int)
or
yourArray.astype(float)