How can I map True/False to 1/0 in a Pandas DataFrame? How can I map True/False to 1/0 in a Pandas DataFrame? numpy numpy

How can I map True/False to 1/0 in a Pandas DataFrame?


A succinct way to convert a single column of boolean values to a column of integers 1 or 0:

df["somecolumn"] = df["somecolumn"].astype(int)


Just multiply your Dataframe by 1 (int)

[1]: data = pd.DataFrame([[True, False, True], [False, False, True]])[2]: print data          0      1     2     0   True  False  True     1   False False  True[3]: print data*1         0  1  2     0   1  0  1     1   0  0  1


True is 1 in Python, and likewise False is 0*:

>>> True == 1True>>> False == 0True

You should be able to perform any operations you want on them by just treating them as though they were numbers, as they are numbers:

>>> issubclass(bool, int)True>>> True * 55

So to answer your question, no work necessary - you already have what you are looking for.

* Note I use is as an English word, not the Python keyword is - True will not be the same object as any random 1.