How can I map True/False to 1/0 in a Pandas DataFrame?
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?
EDIT: 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
dtype=object 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).
1 in Python, and likewise
>>> True == 1 True >>> False == 0 True
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 * 5 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
Truewill not be the same object as any random
★ Back to homepage or read more recommendations: