Reputation: 99
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.
Upvotes: 0
Views: 3942
Reputation: 78554
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
.
Upvotes: 4
Reputation: 5950
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
Upvotes: 4