【问题标题】:Convert pandas datetime to hours from start将熊猫日期时间转换为从开始的小时数
【发布时间】:2019-04-30 23:48:01
【问题描述】:

我有一个具有以下数据时间索引的数据框:

DatetimeIndex(['2018-10-17 00:00:00', '2018-10-17 01:00:00',
               '2018-10-17 02:00:00', '2018-10-17 03:00:00',
               '2018-10-17 04:00:00', '2018-10-17 05:00:00',
               '2018-10-17 06:00:00', '2018-10-17 07:00:00',
               '2018-10-17 08:00:00', '2018-10-17 09:00:00',
               ...
               '2018-11-29 15:00:00', '2018-11-29 16:00:00',
               '2018-11-29 17:00:00', '2018-11-29 18:00:00',
               '2018-11-29 19:00:00', '2018-11-29 20:00:00',
               '2018-11-29 21:00:00', '2018-11-29 22:00:00',
               '2018-11-29 23:00:00', '2018-11-30 00:00:00'],
              dtype='datetime64[ns]', name='dates', length=914, freq=None)

如何将其转换为从第一个日期时间索引开始的小时数,即 0、1、2...

【问题讨论】:

  • 到目前为止你尝试过什么代码?

标签: python pandas datetime indexing


【解决方案1】:

您可以从索引中的所有值中减去第一个日期时间,然后除以 numpy.timedelta(1,'h')(1 小时的时间增量):

(df.index - df.index[0]) / np.timedelta64(1,'h')
Float64Index([   0.0,    1.0,    2.0,    3.0,    4.0,    5.0,    6.0,    7.0,
                 8.0,    9.0, 
                 ...
                 1047.0, 1048.0, 1049.0, 1050.0, 1051.0, 1052.0,
                 1053.0, 1054.0, 1055.0, 1056.0],
             dtype='float64', name='dates')

【讨论】:

  • 您可以添加astype(int) 将其转换为Int64Index。这可能很好,因为 OP 似乎建议所有时间组件都在小时。
【解决方案2】:

您的问题似乎表明索引是这样的,原始时间戳是小时,结果应该是一个整数,在这种情况下,我会修改 sacul 对类似

的回答
24*(idx - idx[0]).days + idx.hour
Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9, 1047,
        1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056],
       dtype='int64', name='dates')

并使用pandas.TimeDeltaIndexcomponents 属性来处理任何剩余的分钟、秒等,以便您只使用已经公开的属性。

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2017-05-20
    相关资源
    最近更新 更多