Home > Software design >  How to change a variable of type object to type boolean in Python?
How to change a variable of type object to type boolean in Python?

Time:09-29

I am not a very experienced Python user, so this might be a very easy question for some people. I have a couple of variables that are set as t or f indicating True or False. When I look up their datatype using df.info(), I see that these variables are objects. However, I want them to become booleans. I looked on the internet but I cannot find a way to do this easily. Is there anyone who can help me out with this problem?

CodePudding user response:

If you start with column with str values of 't' and 'f'

>>> import pandas as pd
>>> df = pd.DataFrame(['t','f','t','f'], columns=['str'])
>>> df
  str
0   t
1   f
2   t
3   f

You can make a new column that does a string comparison that returns a bool representation

>>> df['bool'] = df['str'] == 't'
>>> df
  str   bool
0   t   True
1   f  False
2   t   True
3   f  False
  • Related