Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert boolean to string in DataFrame

Tags:

python

pandas

Stems from this post, but I have found a little issue with the solution.

Using df = df.replace({True: 'TRUE', False: 'FALSE'}), if a value is 1 or 0 it will be replaced. I only want to replace values that are actually True or False of <class 'bool'>.

How can I do this?

like image 278
pstatix Avatar asked Mar 06 '23 10:03

pstatix


1 Answers

You can do this with df.where, so you only replace bool types.

import pandas as pd

mask = df.applymap(type) != bool
d = {True: 'TRUE', False: 'FALSE'}

df = df.where(mask, df.replace(d))

Input:

df = pd.DataFrame({'vals': [1, 0, 1.0, 'True', True, False],
                   'ids': [78, 'kitten', True, False, 'orange', 9]})

Output:

    vals     ids
0      1      78
1      0  kitten
2      1    TRUE
3   True   FALSE
4   TRUE  orange
5  FALSE       9
like image 115
ALollz Avatar answered Mar 28 '23 06:03

ALollz