将Pandas数据框汇总为半小时

时间:2019-05-22 18:35:25

标签: python pandas dataframe datetime

我有一个熊猫数据框,看起来像下面的issue数据框:

import pandas as pd
import datetime

Y = 2017
M = 9

dats = (datetime.datetime(Y, M, M, 15, 30), datetime.datetime(Y, M, M, 16),
        datetime.datetime(Y, M, M, 16, 30), datetime.datetime(Y, M, M, 17),
        datetime.datetime(Y, M, M, 17, 4), datetime.datetime(Y, M, M, 17, 30),
        datetime.datetime(Y, M, M, 18), datetime.datetime(Y, M, M, 18, 30))

issue = {'datetime': dats, 
         '5.0':(2.05, 2.04, 2.04 ,1, float('NaN'), 2.05, 2.04, 5), 
         '6.0':(5.8, 5.9, 5.2, float('NaN'), 6, 6.01, 5, 5.02)}
issue = pd.DataFrame.from_dict(issue)

我想总结一下此数据框中的数据,以仅包含半小时点,并取该半小时内发生的所有值的平均值(nan值除外)。因此,最终目标是要拥有一个类似于下面创建的resolution数据框的数据框:

import pandas as pd
import datetime

Y = 2017
M = 9

dats2 = (datetime.datetime(Y, M, M, 15, 30), datetime.datetime(Y, M, M, 16),
         datetime.datetime(Y, M, M, 16, 30), datetime.datetime(Y, M, M, 17), 
         datetime.datetime(Y, M, M, 17, 30), datetime.datetime(Y, M, M, 18), 
         datetime.datetime(Y, M, M, 18, 30))

resolution = {'datetime': dats2, 
              '5.0':(2.05, 2.04, 2.04 ,1, 2.05, 2.04, 5), 
              '6.0':(5.8, 5.9, 5.2, 6, 6.01, 5, 5.02)}
resolution = pd.DataFrame.from_dict(resolution)

我可以很容易地使用dplyr在R中做到这一点,但是对于Python我还是有些菜鸟。预先感谢您对此事的任何帮助!

1 个答案:

答案 0 :(得分:3)

比R短

issue.set_index('datetime').resample('30 min').mean()
Out[685]: 
                      5.0   6.0
datetime                       
2017-09-09 15:30:00  2.05  5.80
2017-09-09 16:00:00  2.04  5.90
2017-09-09 16:30:00  2.04  5.20
2017-09-09 17:00:00  1.00  6.00
2017-09-09 17:30:00  2.05  6.01
2017-09-09 18:00:00  2.04  5.00
2017-09-09 18:30:00  5.00  5.02