python - 在 panda Dataframe 上使用 IF 命令

标签 python dataframe

我有一个 PandaDataframe,其中包含有关所下订单及其时间的信息。此数据适用于上午 11:00 至凌晨 1:00 营业的餐厅。

数据帧的名称是“DfPayments”。

它有两列 DfPayments['hour'] 和 DfPayments['day'],其中包含有关下订单的日期和时间的信息。汇总当日销售额时,午夜后下的一些订单将计入接下来几天的销售额。因此,我想为小时创建一个新变量,并用它来相应地调整销售额。但是,当我使用以下代码时出现错误。

if DfPayments['hour'] == 0:
    DfPayments['newhour'] = DfPayments['newhour'] - 1

错误是:

---> 18 if DfPayments['hour'] == 0: 19 DfPayments['newhour'] = DfPayments['newhour'] - 1

1574 raise ValueError("The truth value of a {0} is ambiguous. " 1575 "Use a.empty, a.bool(), a.item(), a.any() or a.all()." -> 1576 .format(self.class.name)) 1577 1578 bool = nonzero

最佳答案

使用 bool 索引:

idx = DfPayments['hour']==0
DfPayments.loc[idx, 'newhour'] = DfPayments.loc[idx, 'newhour'] - 1

关于python - 在 panda Dataframe 上使用 IF 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56416128/

相关文章:

python - 模拟电子运动——python中自适应步长的微分方程

r - 使用 dplyr 在数据导入中仅保留一个唯一列

python - pandas 没有将类型 string 转换为 float

python - 如何使用标签中包含 '-' 连字符的列的 pd.DataFrame 对象的查询方法?

python - 将时间列添加到基于另一个 DataFrame 的 DataFrame

python - 匹配 python 正则表达式中的复杂表达式

python - 如何将两个 DataFrame 合并为单个匹配列值

python - 计算 Python 字典列表中具有相同键的元素的数量

python - 将列表中的每一对元素收集到 Python 中的元组中

python - 线条颜色作为 pandas 数据框中列值的函数