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?
This question is related to
python
integer
boolean
type-conversion
scilab
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)
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]
I know you asked for non-looping solutions, but the only solutions I can come up with probably loop internally anyway:
map(int,y)
or:
[i*1 for i in y]
or:
import numpy
y=numpy.array(y)
y*1
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]
A funny way to do this is
>>> np.array([True, False, False]) + 0
np.array([1, 0, 0])
Source: Stackoverflow.com