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

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)