【问题标题】:How to combine date and elapsed time into one datetime column in Python如何在 Python 中将日期和经过时间合并到一个日期时间列中
【发布时间】:2015-10-17 05:52:09
【问题描述】:

我正在尝试将日期列和总经过时间列合并到一个日期时间列中。

我有一个如下所示的 pandas 数据框:

calendarid       actualdeparturetime   actualtriptime                       
2014-01-01       360.066667            26.716667
2014-01-01       384.050000            19.516667
2014-01-01       406.733333            21.900000
2014-01-01       424.850000            17.550000
2014-01-01       444.666667            23.100000

实际出发时间栏是每天经过的总分钟数。 我想将数据框转换为如下所示:

actualdeparturetime   actualtriptime                       
2014-01-01 06:00:04   26.716667
2014-01-01 06:24:03   19.516667
2014-01-01 06:46:44   21.900000
2014-01-01 07:04:51   17.550000
2014-01-01 07:24:40   23.100000

我尝试了几种技术,包括 timedelta 和使用 csv 数据解析器,但我仍在学习,似乎无法靠我自己解决这个问题。有人可以帮忙吗?

我的最终目标是将数据汇总为每天 30 分钟的间隔,然后取每个间隔的实际行程时间的平均值。我假设转换为 datetimeindex 我可以在这些假设下重新采样数据。但是,如果有更好的方法来做到这一点,请告诉我。

【问题讨论】:

    标签: python datetime pandas timedelta


    【解决方案1】:

    使用astype("timedelta64[m]")

    In [608]: df['calendarid'] + df['actualdeparturetime'].astype("timedelta64[m]")
    Out[608]:
    0   2014-01-01 06:00:00
    1   2014-01-01 06:24:00
    2   2014-01-01 06:46:00
    3   2014-01-01 07:04:00
    4   2014-01-01 07:24:00
    dtype: datetime64[ns]
    

    【讨论】:

      【解决方案2】:

      您可以使用简单的加法和pandas.to_datetime()calenderid 列转换为日期时间,并使用pandas.to_timedelta()actualdeparturetime 列转换为timedelta(与unit='m' 参数一起使用以分钟为单位)。示例 -

      df['actualdeparturetime'] = pd.to_datetime(df['calendarid']) + pd.to_timedelta(df['actualdeparturetime'],unit='m')
      

      演示 -

      In [37]: df
      Out[37]:
         calendarid  actualdeparturetime  actualtriptime
      0  2014-01-01           360.066667       26.716667
      1  2014-01-01           384.050000       19.516667
      2  2014-01-01           406.733333       21.900000
      3  2014-01-01           424.850000       17.550000
      4  2014-01-01           444.666667       23.100000
      
      In [38]: df['actualdeparturetime'] = pd.to_datetime(df['calendarid']) + pd.to_timedelta(df['actualdeparturetime'],unit='m')
      
      In [39]: df
      Out[39]:
         calendarid        actualdeparturetime  actualtriptime
      0  2014-01-01 2014-01-01 06:00:04.000020       26.716667
      1  2014-01-01 2014-01-01 06:24:03.000000       19.516667
      2  2014-01-01 2014-01-01 06:46:43.999980       21.900000
      3  2014-01-01 2014-01-01 07:04:51.000000       17.550000
      4  2014-01-01 2014-01-01 07:24:40.000020       23.100000
      

      【讨论】:

      • 谢谢!我一直在努力结合 datetime 和 timedelta 值。这样就搞定了。
      • 很高兴能为您提供帮助! :-) 。另外,如果答案有帮助,我想请您通过单击答案左侧的勾号来接受任何答案(您认为最好/最有帮助的答案),这将对社区有所帮助
      猜你喜欢
      • 2015-12-23
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多