如何将Pandas Dataframe转移/转移到另一年?

时间:2013-09-10 15:17:51

标签: python indexing pandas time-series offset

我有以下15分钟的数据作为数据帧3年。前两列是索引。

2014-01-01 00:15:00  1269.6      
2014-01-01 00:30:00  1161.6      
2014-01-01 00:45:00  1466.4      
2014-01-01 01:00:00  1365.6      
2014-01-01 01:15:00  1362.6      
2014-01-01 01:30:00  1064.0      
2014-01-01 01:45:00  1171.2      
2014-01-01 02:00:00  1171.0      
2014-01-01 02:15:00  1330.4      
2014-01-01 02:30:00  1309.6      
2014-01-01 02:45:00  1308.4      
2014-01-01 03:00:00  1494.0 

我想将数据偏移/转移到上一年,以便将2014-01-01 00:15:00 1269.6转换为2013-01-01 00:15:00 1269.6

我用过     df = df.shift(-1,freq =' 15min') 将数据帧移动15分钟到过去,但不希望偏移/移位15分钟的间隔,因为这可能会导致闰年错误和时钟变化。

有没有人能够顺利解决这个问题?

1 个答案:

答案 0 :(得分:3)

In [13]: df = DataFrame(randn(10,1),index=date_range('20140101 00:15:00',freq='15T',periods=10))

In [14]: df
Out[14]: 
                            0
2014-01-01 00:15:00 -0.176117
2014-01-01 00:30:00  0.517030
2014-01-01 00:45:00  1.033585
2014-01-01 01:00:00 -0.284402
2014-01-01 01:15:00  0.476984
2014-01-01 01:30:00  0.356078
2014-01-01 01:45:00 -0.285609
2014-01-01 02:00:00  0.423048
2014-01-01 02:15:00  0.095823
2014-01-01 02:30:00 -1.123258

In [15]: df.index = df.index-pd.offsets.Day(365)

In [16]: df
Out[16]: 
                            0
2013-01-01 00:15:00 -0.176117
2013-01-01 00:30:00  0.517030
2013-01-01 00:45:00  1.033585
2013-01-01 01:00:00 -0.284402
2013-01-01 01:15:00  0.476984
2013-01-01 01:30:00  0.356078
2013-01-01 01:45:00 -0.285609
2013-01-01 02:00:00  0.423048
2013-01-01 02:15:00  0.095823
2013-01-01 02:30:00 -1.123258