Barry
Barry

Reputation: 256

How to replace type bool in pandas dataframe with strings

I have a dataframe with values:

  Name      Enrolled
JarJar          TRUE
  Boba         FALSE

I want to replace instances of TRUE/FALSE (regardless of case) with TRUE_/FALSE_.

I tried using this code snippet here:

df_to_add = df_to_add.replace('(?i)true', 'TRUE_', regex=True)
df_to_add = df_to_add.replace('(?i)false', 'FALSE_', regex=True)

but nothing happens since the TRUE/FALSE values in the dataframe are currently numpy.bool. How can I work around this?

Upvotes: 0

Views: 579

Answers (2)

Barry
Barry

Reputation: 256

df_to_add.replace({True: 'TRUE_', False: 'FALSE_'}, inplace=True)

Upvotes: 0

imM4TT
imM4TT

Reputation: 282

import pandas as pd

df = pd.DataFrame.from_dict({'Name' : ['JarJar', 'Boba', 'Foo', 'bar', 'foobar', 'foobaaz'], 'Enrolled' : ['TRUE', 'FALSE', 'true', 'false', 'True', 'False']})    
df = df.replace({r"TRUE(?i)": "_TRUE", r"False(?i)": "_FALSE"}, regex=True)

print(df)

Output :

      Name Enrolled
0   JarJar    _TRUE
1     Boba   _FALSE
2      Foo    _TRUE
3      bar   _FALSE
4   foobar    _TRUE
5  foobaaz   _FALSE

Upvotes: 1

Related Questions