python - 有条件地将 1 或 0 设置为新的 Pandas 列

标签 python pandas

<分区>

一个非常简单的 pandas 问题:

如果我有这样的数据框:

   hour
 0  0
 1  1
 2  1
 3  2
 4  2
  ...

我想创建一个新列“午餐”,如果 11<=hour<=1 则值为 1,否则为 0,执行此操作的最佳和计算最快的方法是什么?

最佳答案

你可以

In [231]: df['lunch'] = (df['hour']<=11) & (df['hour']<=1)

In [232]: df['lunch']
Out[232]:
0     True
1     True
2     True
3    False
4    False
Name: lunch, dtype: bool

In [233]: df['lunch'].astype(int)
Out[233]:
0    1
1    1
2    1
3    0
4    0
Name: lunch, dtype: int32

关于python - 有条件地将 1 或 0 设置为新的 Pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32984462/

相关文章:

python - 使用字符串作为变量名 Python

python - 使用 cx_freeze 编译时未找到 ffmpeg 可执行文件

python-3.x - 如何根据概率分布在python中生成随机分类数据?

python - 如何将一系列整数转换为日期?

python - 在解析 JSON 文件数据时,根据 Python 中的配置文件中提到的位置添加具有空值的缺失字段

python - 我收到关键错误 : 'District' for the command df. groupby( ["District"]).sum()[ ['TSP' ,'TSPExp' ]].sort_values( ['TSPExp' ], ascending=[False]).head(3)

python - 使用掩码计算DataFrame中的平均值

python - python中列表的本质,为什么我得到一个重复列表?

python - 通过 3D x、y、z 散点图数据拟合一条线

python - 如何随机排列 Pandas 数据框的行组?