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?
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))
df = pd.DataFrame({'vals': [1, 0, 1.0, 'True', True, False],
'ids': [78, 'kitten', True, False, 'orange', 9]})
vals ids
0 1 78
1 0 kitten
2 1 TRUE
3 True FALSE
4 TRUE orange
5 FALSE 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With