【问题标题】:Combine timedelta and date column, group by time interval结合 timedelta 和 date 列,按时间间隔分组
【发布时间】:2016-01-14 15:11:14
【问题描述】:

我需要将两个单独的列合并为一个日期时间列。

pandas 数据框如下所示:

calendarid    time_delta_actualdeparture    actualtriptime
20140101      0 days 06:35:49.000020000     27.11666667
20140101      0 days 06:51:37.000020000     24.83333333
20140101      0 days 07:11:40.000020000     28.1
20140101      0 days 07:31:40.000020000     23.03333333
20140101      0 days 07:53:34.999980000     23.3
20140101      0 days 08:14:13.000020000     51.81666667

我想把它改成这样:

calendarid               actualtriptime
2014-01-01 6:30:00       mean of trip times in time interval
2014-01-01 7:00:00       mean of trip times in time interval 
2014-01-01 7:30:00       mean of trip times in time interval
2014-01-01 8:00:00       mean of trip times in time interval
2014-01-01 8:30:00       mean of trip times in time interval

基本上我想将这两列合并为一列,然后分组为 30 分钟的时间间隔,取该间隔内实际行程时间的平均值。我尝试了很多技术都没有成功,但我仍在学习 python/pandas。谁能帮我解决这个问题?

【问题讨论】:

    标签: datetime pandas timedelta


    【解决方案1】:

    将您的“日历”列转换为日期时间并添加增量以获得开始时间。

    In [5]: df['calendarid'] = pd.to_datetime(df['calendarid'], format='%Y%m%d')
    
    
    In [7]: df['calendarid'] = df['calendarid'] + df['time_delta_actualdeparture']
    
    In [8]: df
    Out[8]: 
                      calendarid  time_delta_actualdeparture  actualtriptime
    0 2014-01-01 06:35:49.000020             06:35:49.000020       27.116667
    1 2014-01-01 06:51:37.000020             06:51:37.000020       24.833333
    2 2014-01-01 07:11:40.000020             07:11:40.000020       28.100000
    3 2014-01-01 07:31:40.000020             07:31:40.000020       23.033333
    4 2014-01-01 07:53:34.999980             07:53:34.999980       23.300000
    5 2014-01-01 08:14:13.000020             08:14:13.000020       51.816667
    

    然后您可以将日期列设置为索引并以 30 分钟的频率重新采样以获得每个间隔的平均值。

    In [19]: df.set_index('calendarid').resample('30Min', how='mean', label='right')
    Out[19]: 
                         actualtriptime
    calendarid                         
    2014-01-01 07:00:00       25.975000
    2014-01-01 07:30:00       28.100000
    2014-01-01 08:00:00       23.166667
    2014-01-01 08:30:00       51.816667
    

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 2011-12-20
      • 1970-01-01
      • 2011-02-08
      • 2019-06-28
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      相关资源
      最近更新 更多