【问题标题】:Get value From Previous or Next Rows Based on Condition from two or more columns in Python根据 Python 中两列或多列的条件从上一行或下一行中获取值
【发布时间】:2021-09-07 18:32:05
【问题描述】:

我正在使用 Pandas Python 来计算行之间的时间增量,当它使用前一行或下一行时,它是基于条件的。

我的桌子是这样的 sampel table

我想用这个条件创建 timedelta 列: 当 STATUS > status_before 时,它​​会从之前的行中获取值 并在 STATUS

我尝试了几种方法来做到这一点,大多数都以这个错误结束:

The truth value of a Series is ambiguous. Use a.empty, a.bool(),a.item(), a.any() or a.all().

这是我所做的一个例子:

if db.STATUS == 0 and db.status_before == 1:
   db.delta = db['REPORTDATE'].shift()

有什么解决办法吗?

【问题讨论】:

  • 修改您的问题,将您的示例数据显示为符合 SO 准则的文本而不是图像
  • 是的。很抱歉,我会在我可以访问我的电脑后更新我的问题。谢谢。

标签: python pandas if-statement conditional-statements


【解决方案1】:
  • 要获得更高质量的答案,请始终以文本而非图像的形式提供示例数据
  • np.where() 允许您在赋值中使用条件逻辑
  • 你的逻辑没有指定当条件不满足时使用什么值,所以我使用了 REPORTDATE
import numpy as np

df = pd.DataFrame({"REPORTDATE":pd.date_range("2021-06-18", freq="8h", periods=5), "NAMA":["WPP 571"]*5, 
              "PELABUHAN":(["PP Belawan","di laut"]*3)[1:6], "STATUS":([1,0]*3)[0:5],
             "ASAL":(["PP Belawan","di laut"]*3)[0:5], "IGNORED":[0]*5,
             "INSERTTIME":[pd.to_datetime("2021-06-24 09:26:35")]*5})



(
    df.assign(
        status_after=df["STATUS"].shift(-1), status_before=df["STATUS"].shift()
    ).assign(
        timedelta=lambda d: np.where(
            (d.STATUS == 0) & (d["status_before"] == 1),
            d["REPORTDATE"].shift(),
            d["REPORTDATE"],
        )
    )
)

输出

REPORTDATE NAMA PELABUHAN STATUS ASAL IGNORED INSERTTIME status_after status_before timedelta
0 2021-06-18 00:00:00 WPP 571 di laut 1 PP Belawan 0 2021-06-24 09:26:35 0 nan 2021-06-18 00:00:00
1 2021-06-18 08:00:00 WPP 571 PP Belawan 0 di laut 0 2021-06-24 09:26:35 1 1 2021-06-18 00:00:00
2 2021-06-18 16:00:00 WPP 571 di laut 1 PP Belawan 0 2021-06-24 09:26:35 0 0 2021-06-18 16:00:00
3 2021-06-19 00:00:00 WPP 571 PP Belawan 0 di laut 0 2021-06-24 09:26:35 1 1 2021-06-18 16:00:00
4 2021-06-19 08:00:00 WPP 571 di laut 1 PP Belawan 0 2021-06-24 09:26:35 nan 0 2021-06-19 08:00:00

【讨论】:

  • 谢谢,此代码有效!。只是想知道我可以将此代码与 groupby 合并吗?我的原始数据包含唯一的数据组,因此我需要为每个组应用此代码。
  • 差不多,你可以在groupby().apply()groupby().transform()中使用lambda函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 2016-11-01
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多