python - Pandas :使用 if-else 填充新列

标签 python pandas if-statement dataframe

我有一个像这样的 DataFrame:

col1       col2      
  1          0
  0          1
  0          0
  0          0
  3          3
  2          0
  0          4

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

df1[,'col3'] <- ifelse(df1$col2 > 0, 1, 0)

我如何在 python/pandas 中执行此操作?

最佳答案

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

df['col3'] = (df.col2 > 0).astype('int')

(要创建一个新列,您只需为其命名并将其分配给与您的 DataFrame 长度相同的系列、数组或列表。)

这产生 col3 为:

   col2  col3
0     0     0
1     1     1
2     0     0
3     0     0
4     3     1
5     0     0
6     4     1

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

>>> np.where(df['col2'] > 0, 4, -1)
array([-1,  4, -1, -1,  4, -1,  4])

关于python - Pandas :使用 if-else 填充新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29153805/

相关文章:

python - 从旧数据框创建子列

python - 在 pandas apply 函数中获取行的索引

javascript - If else 数组中的简写 .push()

C# LINQ 多行条件

javascript - 变量值检查不起作用

python - 模块导入错误,如何刷新Ipython session ?

python - 从 ftp 下载第二个文件失败

python - django-sentry 的日志记录有哪些轻量级替代品?

python - 使用 python 3 创建虚拟环境时如何修复看似无限循环?

python - 将嵌套字典折叠到 python 中的字典列表中