You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python Dataframe新增列匹配每次pass后首个reception的事件时间

解决方案

使用pandas的内置向后填充功能即可实现,无需编写复杂循环,哪怕pass和reception间隔上百行也能高效运行。

完整可运行代码

import pandas as pd

# 构造示例数据,实际使用时替换为你自己的DataFrame即可
df = pd.DataFrame({
    'event': ['pass', 'failed block', 'failed check', 'reception', 'pass', 'reception'],
    'event time': [10.10, 10.20, 10.21, 10.25, 17.60, 17.65]
})

# 核心逻辑
# 1. 生成临时列,仅event为reception的行保留对应event time,其余行设为空值
df['tmp'] = df['event time'].where(df['event'] == 'reception')
# 2. 对临时列执行向后填充,每一行会自动填充为该行之后第一个出现的reception时间
df['tmp'] = df['tmp'].bfill()
# 3. 仅event为pass的行保留填充后的时间值,其余行返回NA,得到目标列
df['reception time'] = df['tmp'].where(df['event'] == 'pass')
# 删除临时辅助列
df.drop('tmp', axis=1, inplace=True)

# 输出结果验证
print(df)

运行输出结果

event  event time  reception time
0          pass       10.10           10.25
1  failed block       10.20             NaN
2  failed check       10.21             NaN
3     reception       10.25             NaN
4          pass       17.60           17.65
5     reception       17.65             NaN

注意事项

如果你的原始数据没有按event time升序排序,需要先执行排序再运行上述代码,排序代码如下:

df = df.sort_values('event time').reset_index(drop=True)

内容的提问来源于stack exchange,提问作者campbeb2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:54:01