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

Python DataFrame按流程订单计算Type A起始与D结束的时间差

你可以通过pandas分组聚合实现需求,以下是可直接运行的代码:

首先提前预处理数据,剔除Type、Start、End列为空的无效行:

import pandas as pd

# 仅保留计算需要的有效行,剔除空值行
df = df.dropna(subset=['Type', 'Start', 'End'])

# 分组计算时间差逻辑
def get_time_diff(group):
    # 提取当前分组下Type为A的Start值
    a_start_series = group[group['Type'] == 'A']['Start']
    # 提取当前分组下Type为D的End值
    d_end_series = group[group['Type'] == 'D']['End']
    # 两个值都存在才计算,否则返回空值
    if not a_start_series.empty and not d_end_series.empty:
        return d_end_series.iloc[0] - a_start_series.iloc[0]
    return pd.NA

# 按流程订单分组应用计算逻辑,重置索引得到最终结果
result = df.groupby('process order', as_index=False).apply(get_time_diff).rename(columns={None:'Time_difference'})

如果你对应同一个流程订单存在多个Type为A或者Type为D的行,可以根据业务需要调整取值逻辑,比如取最大值.max()、最小值.min()或者按时间排序后取最新值。

运行代码后得到的result就和你要求的输出格式完全一致,无对应取值的流程订单时间差字段会显示为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:27:00