Python 如何在 Pandas DataFrame 中将 True/False 映射到 1/0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17383094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:03:31  来源:igfitidea点击:

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

pythonnumpypandas

提问by Simon Righley

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?

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

采纳答案by User

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

将单列布尔值转换为一列整数 1 或 0 的简洁方法:

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

回答by Gareth Latty

Trueis 1in Python, and likewise Falseis 0*:

True1在Python,同样False0*

>>> 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 arenumbers:

您应该能够通过将它们视为数字来执行您想要的任何操作,因为它们数字:

>>> 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 isas an English word, not the Python keyword is- Truewill not be the same object as any random 1.

* 注意我使用is作为英文单词,而不是 Python 关键字is-True不会与任何 random 相同的对象1

回答by Jeff

You also can do this directly on Frames

您也可以直接在 Frames 上执行此操作

In [104]: df = DataFrame(dict(A = True, B = False),index=range(3))

In [105]: df
Out[105]: 
      A      B
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]: 
   A  B
0  1  0
1  1  0
2  1  0

In [108]: df.astype(int).dtypes
Out[108]: 
A    int64
B    int64
dtype: object

回答by shubhamgoel27

Just multiply your Dataframe by 1 (int)

只需将您的 Dataframe 乘以 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

回答by Bruno Benevides

You can use a transformation for your data frame:

您可以对数据框使用转换:

df = pd.DataFrame(my_data condition)

transforming True/False in 1/0

在 1/0 中转换 True/False

df = df*1

回答by jezrael

Use Series.viewfor convert boolean to integers:

使用Series.view的转换布尔为整数:

df["somecolumn"] = df["somecolumn"].view('i1')