Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert true false values in dataframe as 1 for true and 0 for false

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 
like image 827
Ashim Sinha Avatar asked Apr 30 '15 06:04

Ashim Sinha


People also ask

How do you change true/false to 1 0 in Python?

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.

How do you convert true to false in Python?

In Python, 1 denotes True , and 0 denotes False . So, the tilde operator converts True to False and vice-versa.


1 Answers

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) 
like image 165
abarnert Avatar answered Oct 11 '22 08:10

abarnert