pandas:使用if-else填充新列

scr*_*Owl 6 python if-statement dataframe pandas

我有一个像这样的DataFrame:

col1       col2      
  1          0
  0          1
  0          0
  0          0
  3          3
  2          0
  0          4
Run Code Online (Sandbox Code Playgroud)

如果col2> 0或0,我想添加一个1的列.如果我使用R,我会做类似的事情

df1[,'col3'] <- ifelse(df1$col2 > 0, 1, 0)
Run Code Online (Sandbox Code Playgroud)

我怎么能在python/pandas中这样做?

Ale*_*ley 8

您可以将布尔系列转换为df.col2 > 0整数系列(True变为1False变为0):

df['col3'] = (df.col2 > 0).astype('int')
Run Code Online (Sandbox Code Playgroud)

(要创建新列,只需将其命名并将其分配给与DataFrame长度相同的Series,数组或列表.)

这产生col3如下:

   col2  col3
0     0     0
1     1     1
2     0     0
3     0     0
4     3     1
5     0     0
6     4     1
Run Code Online (Sandbox Code Playgroud)

另一种创建列的方法可能是使用np.where,它允许您为true或false值指定值,并且可能更接近R函数的语法ifelse.例如:

>>> np.where(df['col2'] > 0, 4, -1)
array([-1,  4, -1, -1,  4, -1,  4])
Run Code Online (Sandbox Code Playgroud)