pandas 将熊猫数据框中的整数二进制化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40717156/
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
Binarize integer in a pandas dataframe
提问by matthew
I have a pandas dataframe and want to add a new column. For all values in 'number' which are smaller than 15 I want to add 1, for all values which are greater, 0. I tried different methods, but I don't receive the desired result.Especially, because I have problems with the structure. Here is what I wanna do:
我有一个Pandas数据框,想添加一个新列。对于“数字”中小于 15 的所有值,我想加 1,对于所有大于 0 的值。我尝试了不同的方法,但没有得到想要的结果。特别是,因为我有问题结构体。这是我想做的:
number binary
12 1
89 0
12 1
56 0
62 0
2 1
657 0
5 1
73 0
回答by Zero
In [6]: (df['number'] < 15).astype(int)
Out[6]:
0 1
1 0
2 1
3 0
4 0
5 1
6 0
7 1
8 0
Name: number, dtype: int32
In [7]: df['binary'] = (df['number'] < 15).astype(int)
In [8]: df
Out[8]:
number binary
0 12 1
1 89 0
2 12 1
3 56 0
4 62 0
5 2 1
6 657 0
7 5 1
8 73 0
回答by p-robot
You can convert it to boolean then multiply by 1.
您可以将其转换为布尔值,然后乘以 1。
import pandas as pd
df = pd.DataFrame({'number': [12, 89, 12, 56, 62, 2, 657, 5, 73]})
df['binary'] = (df.number < 15)*1