0

I have this dataframe

data = [['Tom', 16, 'True','False'], ['Nick', 19, 'False','True'], ['Juli', 17, 'True','True']] 
df = pd.DataFrame(data, columns = ['Name', 'Age', 'Writer','Artist']) 

I want to convert the string booleans to booleans.

I have tried

def str_to_bool(s):
    if s == 'True':
         return True
    elif s == 'False':
         return False
    else:
         raise ValueError

df[['Writer','Artist']] = df[['Writer','Artist']].apply(str_to_bool)

and

import ast
df[['Writer','Artist']] = df['Writer','Artist'].map(ast.literal_eval)

but neither of these worked.

Is it possible to do convert the type of multiple columns in a single line or do I have to convert the relevant columns one at a time?

2 Answers 2

2

You can use the dictionary version of replace.

df = df.replace({'True': True, 'False': False})

df
   Name  Age  Writer  Artist
0   Tom   16    True   False
1  Nick   19   False    True
2  Juli   17    True    True

dtypes
Name      object
Age        int64
Writer      bool
Artist      bool
dtype: object

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

Comments

-1

you could just do:

df['Writer'].apply(eval)

output:

>>> df['Writer'].apply(eval)
0     True
1    False
2     True
Name: Writer, dtype: bool

Comments

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.