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

我有一个pythonpandasDataFrame具有布尔True / False值的列,但为了进一步计算,我需要1/0表示。 有没有一个快速的pandas/ numpy的方式来做到这一点?

编辑:下面的答案似乎并没有举行的情况下numpy,给定一个数组与整数和True / False值,返回这样的数组dtype=object 。 为了在numpy中继续进行计算,我必须明确地设置np_values = np.array(df.values, dtype = np.float64)

在Python中True1 ,同样False0 *

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

你应该能够对他们进行任何操作,只要把它们看作是数字,就像数字一样:

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

所以要回答你的问题,没有必要的工作 – 你已经有你在找什么。

*注意我使用的一个英文单词,而不是Python关键字isTrue不会是任何随机的1

只是非常明确地回答如何将一列布尔值转换为整数1或0的列的问题:

df.somecolumn = df.somecolumn.astype(int)

你也可以直接在框架上做到这一点

 In [104]: df = DataFrame(dict(A = True, B = False),index=range(3)) In [105]: df Out[105]: AB 0 True False 1 True False 2 True False In [106]: df.dtypes Out[106]: A bool B bool dtype: object In [107]: df.astype(int) Out[107]: AB 0 1 0 1 1 0 2 1 0 In [108]: df.astype(int).dtypes Out[108]: A int64 B int64 dtype: object 

只要乘以你的dataframe1(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