I have a dataframe that has about 100 columns, There are some Boolean columns and some chars. I want to replace all Boolean having values True/False and also -1 with 1/0. I want to apply it on whole dataframe instead of single column.
I saw some solutions here, like converting the column to integer. But I want to avoid the exercise of going through 100s of columns.
Here is something I tried unsuccessfully:
test.applymap(lambda x: 1 if x=='True' else x)
test.applymap(lambda x: 0 if x=='False' else x)
But the dataframe test still has True/False
applymap
is not in-place by default, it will return a new dataframe.
The correct way:
test = test.applymap(lambda x: 1 if x == True else x)
test = test.applymap(lambda x: 0 if x == False else x)
or
test = test.applymap(lambda x: 1 if x == True else x).test.applymap(lambda x: 0 if x=='False' else x)
or simply
test.applymap(lambda x: 1 if x == True else x, inplace=True)
test.applymap(lambda x: 0 if x == False else x, inplace=True)
Although replace
seems the best way of achieving this:
test.replace(False, 0, inplace=True)
For a single column, the simplest way by far is to convert the column type. Pandas is smart enough to map boolean to int correctly.
df.column_name = df.column_name.astype(int)
If df.column_name starts as Boolean
, it will become zeros and ones after converting to type int
Define a function that loops the .replace() through each column of the Dataframe:
def replace_boolean(data):
for col in data:
data[col].replace(True, 1, inplace=True)
data[col].replace(False, 0, inplace=True)
replace_boolean(test)
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