【问题标题】:insert record to fill missing time window插入记录以填充缺失的时间窗口
【发布时间】:2023-02-22 00:48:38
【问题描述】:

我有一个数据集,其中包含与活动(驾驶、休息、充电等)相对应的连续时间段。但是晚上没有记录所以数据不连续。我想添加一条额外的记录来填补这一空白,以便每条记录的开始时间始终等于前一条记录的结束时间。自动插入这些记录的最佳方式是什么(对于不同的车辆 ID)。我的数据现在看起来像这样:

import pandas as pd
from io import StringIO

csv = """
id,starttime,endtime
1,2022-09-19 17:05:00,2022-09-19 17:26:00
1,2022-09-19 17:26:00,2022-09-19 18:38:00
1,2022-09-19 18:38:00,2022-09-19 19:31:00
1,2022-09-19 19:31:00,2022-09-19 19:38:00
1,2022-09-19 19:38:00,2022-09-19 19:40:00
1,2022-09-19 19:40:00,2022-09-19 19:41:00
1,2022-09-20 07:06:00,2022-09-20 07:06:00
1,2022-09-20 07:06:00,2022-09-20 07:23:00
1,2022-09-20 07:23:00,2022-09-20 07:26:00
1,2022-09-20 07:26:00,2022-09-20 07:37:00
"""

df = pd.read_csv(StringIO(csv))

我想添加额外的记录:

1,2022-09-19 19:41:00,2022-09-20 07:06:00

(在实际情况下多天和多个 id)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    注释代码

    # Shift the rows in endtime per id
    df['lag'] = df.groupby('id')['endtime'].shift()
    
    # boolean condition to identify rows where startime
    # of current row is not equal to end time of previous row
    mask = (df['starttime'] !=  df['lag']) & df['lag'].notna()
    
    # select the rows where condtion is True and set old starttime 
    # to new endtime and lag to the new starttime
    rows = df[mask].drop(columns=['endtime'])
    rows = rows.rename(columns={'starttime': 'endtime', 'lag': 'starttime'})
    
    # Realign index to ensure the order while sorting in next step
    rows.index -= 1 
    
    # append the new rows and sort the index
    result = pd.concat([df, rows]).sort_index(ignore_index=True).drop(columns='lag')
    

    结果

        id            starttime              endtime
    0    1  2022-09-19 17:05:00  2022-09-19 17:26:00
    1    1  2022-09-19 17:26:00  2022-09-19 18:38:00
    2    1  2022-09-19 18:38:00  2022-09-19 19:31:00
    3    1  2022-09-19 19:31:00  2022-09-19 19:38:00
    4    1  2022-09-19 19:38:00  2022-09-19 19:40:00
    5    1  2022-09-19 19:40:00  2022-09-19 19:41:00
    6    1  2022-09-19 19:41:00  2022-09-20 07:06:00 # -- inserted row --
    7    1  2022-09-20 07:06:00  2022-09-20 07:06:00
    8    1  2022-09-20 07:06:00  2022-09-20 07:23:00
    9    1  2022-09-20 07:23:00  2022-09-20 07:26:00
    10   1  2022-09-20 07:26:00  2022-09-20 07:37:00
    

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2012-09-05
      相关资源
      最近更新 更多