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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18722786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:08:42  来源:igfitidea点击:

How to offset/shift a Pandas Dataframe into another year?

pythonindexingpandastime-seriesoffset

提问by Markus W

I have the following 15 minute data as a dataframe for 3 years. With the first two columns being the index.

我有以下 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 

I would like to offset/shift the data into the previous year so that 2014-01-01 00:15:00 1269.6will be converted into 2013-01-01 00:15:00 1269.6.

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

I have used df = df.shift(-1, freq='15min') to shift the dataframe 15 mins into the past but would not like to offset/shift by the number of 15min intervals as this might cause errors in leap years and with clock changes.

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

Does anyone have a smooth solution for this?

有没有人对此有一个顺利的解决方案?

回答by Jeff

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