How to convert true false values in Dataframe as 1 for true and 0 for false
COL1 COL2 COL3 COL4 12 TRUE 14 FALSE 13 FALSE 13 TRUE OUTPUT 12 1 14 0 13 0 13 1
In Python True and False are equivalent to 1 and 0. Use the int() method on a boolean to get its int values. int() turns the boolean into 1 or 0. Note: that any value not equal to 'true' will result in 0 being returned.
In Python, 1 denotes True , and 0 denotes False . So, the tilde operator converts True to False and vice-versa.
First, if you have the strings 'TRUE'
and 'FALSE'
, you can convert those to boolean True
and False
values like this:
df['COL2'] == 'TRUE'
That gives you a bool
column. You can use astype
to convert to int
(because bool
is an integral type, where True
means 1
and False
means 0
, which is exactly what you want):
(df['COL2'] == 'TRUE').astype(int)
To replace the old string column with this new int
column, just assign it:
df['COL2'] = (df['COL2'] == 'TRUE').astype(int)
And to do that to two columns at one, just index with a list of columns:
df[['COL2', 'COL4']] = (df[['COL2', 'COL4']] == 'TRUE').astype(int)
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