0

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

then what is the solution to get the output i WANT
elif s should be elif string Also to be compatible with OPs data, the comparison should be to 'TRUE' and 'FALSE'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.