在熊猫中更改日期时间轴?

时间:2016-11-02 18:16:07

标签: python datetime pandas matplotlib

我用以下日期时间轴制作了一个情节。

enter image description here

我怎样才能改变它,从早上6点开始到凌晨3点结束(而不是从晚上7点开始到下午4点结束)?如果它是相关的,这就是我制作情节的方式:

<div>

其中df是pandas dataframe。

1 个答案:

答案 0 :(得分:1)

使用tshift方法将索引中的所有日期更改指定数量的偏移量。(假设索引是日期时间对象)。

<强> 演示:

from datetime import datetime
index = pd.date_range(start=datetime(2016,10,6,19), end=datetime(2016,10,7,16), freq='3H')
df = pd.DataFrame(np.random.randint(0,10, (8,1)), index=index)
df.index

给出:

DatetimeIndex(['2016-10-06 19:00:00', '2016-10-06 22:00:00',
               '2016-10-07 01:00:00', '2016-10-07 04:00:00',
               '2016-10-07 07:00:00', '2016-10-07 10:00:00',
               '2016-10-07 13:00:00', '2016-10-07 16:00:00'],
              dtype='datetime64[ns]', freq='3H')

选择offfset以创建延迟。

df.tshift(-13, freq='H').index

给出:

DatetimeIndex(['2016-10-06 06:00:00', '2016-10-06 09:00:00',
               '2016-10-06 12:00:00', '2016-10-06 15:00:00',
               '2016-10-06 18:00:00', '2016-10-06 21:00:00',
               '2016-10-07 00:00:00', '2016-10-07 03:00:00'],
              dtype='datetime64[ns]', freq='3H')

这样可以保持列值不变,并且不会产生任何偏移。它只是改变(移动)索引轴。