pandas 熊猫:使用 if-else 填充新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29153805/
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
pandas: Use if-else to populate new column
提问by screechOwl
I have a DataFrame like this:
我有一个像这样的数据帧:
col1 col2
1 0
0 1
0 0
0 0
3 3
2 0
0 4
I'd like to add a column that is a 1 if col2 is > 0 or 0 otherwise. If I was using R I'd do something like
如果 col2 > 0 或 0,我想添加一个为 1 的列。如果我使用 R 我会做类似的事情
df1[,'col3'] <- ifelse(df1$col2 > 0, 1, 0)
How would I do this in python / pandas?
我将如何在 python/pandas 中做到这一点?
回答by Alex Riley
You could convert the boolean series df.col2 > 0to an integer series (Truebecomes 1and Falsebecomes 0):
您可以将布尔系列转换为df.col2 > 0整数系列(True变成1和False变成0):
df['col3'] = (df.col2 > 0).astype('int')
(To create a new column, you simply need to name it and assign it to a Series, array or list of the same length as your DataFrame.)
(要创建一个新列,您只需为其命名并将其分配给与您的 DataFrame 长度相同的系列、数组或列表。)
This produces col3as:
这产生col3为:
col2 col3
0 0 0
1 1 1
2 0 0
3 0 0
4 3 1
5 0 0
6 4 1
Another way to create the column could be to use np.where, which lets you specify a value for either of the true or false values and is perhaps closer to the syntax of the R function ifelse. For example:
创建列的另一种方法是使用np.where,它允许您为 true 或 false 值指定一个值,并且可能更接近 R 函数的语法ifelse。例如:
>>> np.where(df['col2'] > 0, 4, -1)
array([-1, 4, -1, -1, 4, -1, 4])
回答by Alexander
I assume that you're using Pandas (because of the 'df' notation). If so, you can assign col3 a boolean flag by using .gt (greater than) to compare col2 against zero. Multiplying the result by one will convert the boolean flags into ones and zeros.
我假设您使用的是 Pandas(因为 'df' 表示法)。如果是这样,您可以通过使用 .gt(大于)将 col2 与零进行比较来为 col3 分配一个布尔标志。将结果乘以 1 会将布尔标志转换为 1 和 0。
df1 = pd.DataFrame({'col1': [1, 0, 0, 0, 3, 2, 0],
'col2': [0, 1, 0, 0, 3, 0, 4]})
df1['col3'] = df1.col2.gt(0) * 1
>>> df1
Out[70]:
col1 col2 col3
0 1 0 0
1 0 1 1
2 0 0 0
3 0 0 0
4 3 3 1
5 2 0 0
6 0 4 1
You can also use a lambda expression to achieve the same result, but I believe the method above is simpler for your given example.
您也可以使用 lambda 表达式来实现相同的结果,但我相信上面的方法对于您给定的示例更简单。
df1['col3'] = df1['col2'].apply(lambda x: 1 if x > 0 else 0)

