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

Pandas如何提取DataFrame每行各扫描环节最早时间生成新列

实现代码

import pandas as pd

# 原始DataFrame
df = pd.DataFrame({
    "Transaction":["ett852741963", "ett123654789", "ett753951852", "ett159753852"],
    "Arrival Scan":["02-11-2021 23:45:21", "", "05-11-2021 06:12:10", "04-11-2021 08:19:36"],
    "Unloading Scan":["", "03-11-2021 06:14:22", "03-11-2021 11:41:22", "04-11-2021 14:45:21"],
    "Unpacking Scan":["", "03-11-2021 8:02:11", "02-11-2021 15:01:02", ""],
    "Delivery Scan":["04-11-2021 08:32:10", "", "03-11-2021 17:45:16", ""]
})

# 定义需要计算的扫描环节列
scan_cols = ["Arrival Scan", "Unloading Scan", "Unpacking Scan", "Delivery Scan"]

# 把空值转成时间缺失标记,统一转为日期时间格式(原始时间为日-月-年结构)
df[scan_cols] = df[scan_cols].replace("", pd.NA).apply(pd.to_datetime, format="%d-%m-%Y %H:%M:%S", errors="coerce")

# 按行取最早时间,再转回和原始格式一致的字符串
df["First Time"] = df[scan_cols].min(axis=1).dt.strftime("%d-%m-%Y %H:%M:%S").fillna("")

# 如需保留原始时间列为字符串格式,加下面这行即可
df[scan_cols] = df[scan_cols].dt.strftime("%d-%m-%Y %H:%M:%S").fillna("")

运行上述代码后得到的DataFrame和要求的输出格式完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:36:11