【问题标题】:How to calculate time-delta between (row 1 and 2) and (row 3 and 4) and so on?如何计算(第 1 行和第 2 行)和(第 3 行和第 4 行)之间的时间增量等等?
【发布时间】:2021-05-14 19:00:00
【问题描述】:

我有数据集,

ID     Date
1   12/12/2020 13:00
1   12/12/2020 14:00
1   12/12/2020 15:00
1   12/12/2020 16:00
2   12/13/2020 13:00
2   12/13/2020 13:15
2   12/13/2020 14:00
2   12/13/2020 14:30

预期输出,

ID   TimeDelta
1     120mins
2     45mins

我需要为每个 GROUPBY 找出(第 1 行和第 2 行)、(第 3 行和第 4 行)等之间的时间差,然后添加差异

【问题讨论】:

    标签: python pandas timestamp pandas-groupby timedelta


    【解决方案1】:

    一种方法是枚举行,然后旋转:

    enum = df.groupby('ID').cumcount()
    df['col'] = enum % 2
    df['row'] = enum //2
    
    tmp = df.pivot_table(index=['ID','row'], columns='col', 
                         values='Date', aggfunc='first')
    tmp[1].sub(tmp[0]).sum(level=0)
    

    输出:

    ID
    1   0 days 02:00:00
    2   0 days 00:45:00
    dtype: timedelta64[ns]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2011-03-30
      • 1970-01-01
      相关资源
      最近更新 更多