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

如何用Python基于Reboot列的Initiated/Completed记录计算BootTime

解决BootTime计算错误的问题

你的问题出在当前代码是用每个MacAddress组的第一条记录时间来计算差值,而不是每条Completed记录对应的最近的上一条Initiated记录时间。这就是为什么Shreya的第3、4行BootTime结果不符合预期——它们应该和紧邻的上一条Initiated计算时间差,而不是组里的第一条Initiated。

下面是修正后的完整代码,完全符合你的期望输出:

import pandas as pd

# 创建数据集
d = {'MacAddress': ['Karan', 'Shreya', 'Shreya', 'Shreya', 'Shreya', 'Karan'],
     'Datetime': ['2015-02-24 19:12:00', '2015-02-24 21:38:00', '2015-02-25 03:41:00', 
                  '2015-02-25 03:44:00', '2015-02-25 03:45:00', '2015-02-25 03:49:00'],
     'Reboot': ['Initiated', 'Initiated', 'Completed', 'Initiated', 'Completed', 'Completed']}
df = pd.DataFrame(d, columns=['MacAddress', 'Datetime', 'Reboot'])

# 转换为带UTC时区的datetime类型
df['Datetime'] = pd.to_datetime(df['Datetime']).dt.tz_localize('UTC')

# 定义处理每个分组的函数
def calculate_boot_time(group):
    # 为每条记录填充最近的上一条Initiated的时间
    group['last_initiated'] = group[group['Reboot'] == 'Initiated']['Datetime'].ffill()
    # 计算BootTime:Initiated记录设为0,Completed记录计算时间差
    group['BootTime'] = group.apply(
        lambda row: pd.Timedelta(0) if row['Reboot'] == 'Initiated' 
        else row['Datetime'] - row['last_initiated'],
        axis=1
    )
    # 将Timedelta转换为HH:MM:SS格式的字符串
    group['BootTime'] = group['BootTime'].apply(
        lambda td: f"{td.components.hours:02d}:{td.components.minutes:02d}:{td.components.seconds:02d}"
    )
    # 移除临时辅助列
    return group.drop(columns=['last_initiated'])

# 按MacAddress分组处理数据
df = df.groupby('MacAddress', group_keys=False).apply(calculate_boot_time)

print(df)

代码工作原理

  1. 填充最近的Initiated时间:通过group[group['Reboot'] == 'Initiated']['Datetime'].ffill(),我们筛选出每个分组里所有Initiated的时间,然后向前填充到后续的记录中,这样每条Completed记录都会关联到最近的上一条Initiated时间。
  2. 计算时间差:对Initiated记录直接设置BootTime为00:00:00;对Completed记录,用当前Datetime减去填充的last_initiated时间得到时间差。
  3. 格式转换:把Timedelta类型的时间差转换成HH:MM:SS格式的字符串,确保输出格式和期望一致。

运行结果

MacAddress                  Datetime     Reboot BootTime
0      Karan 2015-02-24 19:12:00+00:00  Initiated  00:00:00
1     Shreya 2015-02-24 21:38:00+00:00  Initiated  00:00:00
2     Shreya 2015-02-25 03:41:00+00:00  Completed  06:03:00
3     Shreya 2015-02-25 03:44:00+00:00  Initiated  00:00:00
4     Shreya 2015-02-25 03:45:00+00:00  Completed  00:01:00
5      Karan 2015-02-25 03:49:00+00:00  Completed  08:37:00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:17:55