The Python Oracle

Converting all occurrence of True/False to 1/0 in a dataframe with mixed datatype

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC I Beethoven Sonata No 31 in A Flat M

--

Chapters
00:00 Question
00:50 Accepted answer (Score 12)
01:27 Answer 2 (Score 5)
01:56 Answer 3 (Score 1)
02:14 Answer 4 (Score 0)
02:32 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