编程语言
首页 > 编程语言> > python-如何在熊猫中将时间序列数据从昨天移到今天?

python-如何在熊猫中将时间序列数据从昨天移到今天?

作者:互联网

我的数据帧低于当天(12-02〜1203).我想每天将昨天的数据(12-02 22:00〜00:00)移至今天的数据(12-03).日期/时间是多索引的.当我分析数据时,这是必需的,它一天比一天更方便.但是现在我需要分析包括昨天过去2小时在内的数据…所以我需要此数据帧操作.

..
 date         time       a     b 
2015-12-02  21:00:00    23.97   0
2015-12-02  21:15:00    24.06   0
2015-12-02  21:30:00    24.03   0
2015-12-02  21:45:00    23.99   0
2015-12-02  22:00:00    24.03   0
2015-12-02  22:15:00    23.89   0
2015-12-02  22:30:00    23.71   0
2015-12-02  22:45:00    23.64   0
2015-12-02  23:00:00    23.29   0
2015-12-02  23:15:00    23.8    0
2015-12-02  23:30:00    23.82   0
2015-12-02  23:45:00    23.86   0
2015-12-03  0:00:00 23.66   0
2015-12-03  0:15:00 23.64   0
2015-12-03  0:30:00 23.7    0
2015-12-03  0:45:00 23.69   0
2015-12-03  1:00:00 23.65   0
2015-12-03  1:15:00 23.48   0
2015-12-03  1:30:00 23.45   0
..

结果应该如下所示(12-02 22:00〜23:45数据移至12-03我该怎么办?

..
2015-12-02  21:00:00    23.97   0
2015-12-02  21:15:00    24.06   0
2015-12-02  21:30:00    24.03   0
2015-12-02  21:45:00    23.99   0
2015-12-03  22:00:00    24.03   0
2015-12-03  22:15:00    23.89   0
2015-12-03  22:30:00    23.71   0
2015-12-03  22:45:00    23.64   0
2015-12-03  23:00:00    23.29   0
2015-12-03  23:15:00    23.8    0
2015-12-03  23:30:00    23.82   0
2015-12-03  23:45:00    23.86   0
2015-12-03  0:00:00 23.66   0
2015-12-03  0:15:00 23.64   0
2015-12-03  0:30:00 23.7    0
2015-12-03  0:45:00 23.69   0
2015-12-03  1:00:00 23.65   0
2015-12-03  1:15:00 23.48   0
2015-12-03  1:30:00 23.45   0
..

解决方法:

我认为您需要:

from datetime import date, datetime, time, timedelta

m = df.index.get_level_values(1) < time(22,0,0)
idx1 = df.index.get_level_values(0)
idx2 = df.index.get_level_values(1)
df.index = [idx1.where(m, idx1 +  timedelta(days=1)), idx2]

print (df)
                         a  b
date       time              
2015-12-02 21:00:00  23.97  0
           21:15:00  24.06  0
           21:30:00  24.03  0
           21:45:00  23.99  0
2015-12-03 22:00:00  24.03  0
           22:15:00  23.89  0
           22:30:00  23.71  0
           22:45:00  23.64  0
           23:00:00  23.29  0
           23:15:00  23.80  0
           23:30:00  23.82  0
           23:45:00  23.86  0
           00:00:00  23.66  0
           00:15:00  23.64  0
           00:30:00  23.70  0
           00:45:00  23.69  0
           01:00:00  23.65  0
           01:15:00  23.48  0
           01:30:00  23.45  0

标签:pandas,move,time-series,python
来源: https://codeday.me/bug/20191109/2013149.html