Simon Righley Simon Righley - 8 months ago 42
Python Question

python pandas/numpy True/False to 1/0 mapping

I have a column in python pandas DataFrame that has boolean True/False values, but for further calculations I need 1/0 representation. Is there a quick pandas/numpy way to do that?

The answers below do not seem to hold in the case of numpy that, given an array with both integers and True/False values, returns

on such array. In order to proceed with further calculations in numpy, I had to set explicitly
np_values = np.array(df.values, dtype = np.float64)


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

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

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 * 5

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.