Converting all occurrence of True/False to 1/0 in a dataframe with mixed datatype
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 Converting All Occurrence Of True/False To 1/0 In A Dataframe With Mixed Datatype
00:38 Accepted Answer Score 13
01:08 Answer 2 Score 1
01:22 Answer 3 Score 5
01:44 Answer 4 Score 0
01:55 Thank you
--
Full question
https://stackoverflow.com/questions/3849...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datamanipulation
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping
--
Chapters
00:00 Converting All Occurrence Of True/False To 1/0 In A Dataframe With Mixed Datatype
00:38 Accepted Answer Score 13
01:08 Answer 2 Score 1
01:22 Answer 3 Score 5
01:44 Answer 4 Score 0
01:55 Thank you
--
Full question
https://stackoverflow.com/questions/3849...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datamanipulation
#avk47
ACCEPTED ANSWER
Score 13
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)
ANSWER 2
Score 5
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
ANSWER 3
Score 1
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)
ANSWER 4
Score 0
You can do it easily using multiplication by 1. If you do that, all your Data Frame will be transformed:
df*1