Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from boolean array to int array in python

Tags:

python

numpy

I have a Numpy 2-D array in which one column has Boolean values i.e. True/False. I want to convert it to integer 1 and 0 respectively, how can I do it?

E.g. my data[0::,2] is boolean, I tried

data[0::,2]=int(data[0::,2])

, but it is giving me error:

TypeError: only length-1 arrays can be converted to Python scalars

My first 5 rows of array are:

[['0', '3', 'True', '22', '1', '0', '7.25', '0'],
 ['1', '1', 'False', '38', '1', '0', '71.2833', '1'],
 ['1', '3', 'False', '26', '0', '0', '7.925', '0'],
 ['1', '1', 'False', '35', '1', '0', '53.1', '0'],
 ['0', '3', 'True', '35', '0', '0', '8.05', '0']]
like image 648
Akashdeep Saluja Avatar asked Jun 01 '13 06:06

Akashdeep Saluja


2 Answers

Ok, the easiest way to change a type of any array to float is doing:

data.astype(float)

The issue with your array is that float('True') is an error, because 'True' can't be parsed as a float number. So, the best thing to do is fixing your array generation code to produce floats (or, at least, strings with valid float literals) instead of bools.

In the meantime you can use this function to fix your array:

def boolstr_to_floatstr(v):
    if v == 'True':
        return '1'
    elif v == 'False':
        return '0'
    else:
        return v

And finally you convert your array like this:

new_data = np.vectorize(boolstr_to_floatstr)(data).astype(float)
like image 82
kirelagin Avatar answered Oct 20 '22 14:10

kirelagin


boolarrayvariable.astype(int) works:

data = np.random.normal(0,1,(1,5))
threshold = 0
test1 = (data>threshold)
test2 = test1.astype(int)

Output:

data = array([[ 1.766, -1.765,  2.576, -1.469,  1.69]])
test1 = array([[ True, False,  True, False,  True]], dtype=bool)
test2 = array([[1, 0, 1, 0, 1]])
like image 13
aslan Avatar answered Oct 20 '22 16:10

aslan