简体   繁体   中英

convert python list to numpy array boolean

I have a big list in python like small example and want to make a numpy array which is boolean.

small example:

li = ['FALSE', 'FALSE', 'TRUE', 'FALSE', 'FALSE', 'FALSE']

I tried to change it using the following line:

out = array(li, dtype = bool)

and then I got this output:

out = array([ True, True, True, True, True, True], dtype=bool)

but the problem is that they are all True. how can I make the same array but elements should remain the same meaning False should be False and True should be True in the new array.

You can convert the strings to boolean literals using str.title and ast.literal_eval :

import ast
import numpy as np

li = ['FALSE', 'FALSE', 'TRUE', 'FALSE', 'FALSE', 'FALSE']
arr = np.array([ast.literal_eval(x.title()) for x in li])
# array([False, False,  True, False, False, False], dtype=bool)

You could otherwise use a simple list comprehension if you have only those two in your list:

arr = np.array([x=='TRUE' for x in li])
# array([False, False,  True, False, False, False], dtype=bool)

Keep in mind that non-empty strings are truthy , so coercing them to bool like you did will produce an array with all elements as True .

bool('True') and bool('False') always return True because strings 'True' and 'False' are not empty

You can create afunction to convert string to bool

def string_to_bool(string):
    if string == 'True':
        return True
    elif string == 'False':
        return False
>>> string_to_bool('True')
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM