每 2 小时对一个数据框的数据进行分组

Dhe*_*raj 3 python dataframe pandas pandas-groupby

我有一个数据框:

                    Time  T201FN1ST2010  T201FN1VT2010
1791 2017-12-26 00:00:00         854.69           0.87
1792 2017-12-26 00:20:00         855.76           0.87
1793 2017-12-26 00:40:00         854.87           0.87
1794 2017-12-26 01:00:00         855.51           0.87
1795 2017-12-26 01:20:00         856.35           0.86
1796 2017-12-26 01:40:00         856.13           0.86
1797 2017-12-26 02:00:00         855.84           0.85
1798 2017-12-26 02:20:00         856.58           0.85
1799 2017-12-26 02:40:00         856.37           0.85
1800 2017-12-26 03:00:00         855.35           0.86
1801 2017-12-26 03:20:00         855.68           0.86
1802 2017-12-26 03:40:00         855.45           0.85
1803 2017-12-26 04:00:00         855.50           0.85
1804 2017-12-26 04:20:00         855.84           0.85
1805 2017-12-26 04:40:00         856.47           0.85
1806 2017-12-26 05:00:00         855.29           0.86
1807 2017-12-26 05:20:00         855.45           0.87
1808 2017-12-26 05:40:00         855.80           0.86
1809 2017-12-26 06:00:00         854.93           0.88
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 groupby 对每两个小时的数据进行分组,但我无法做到。

我试过这个:

last8.groupby(last8.Time.dt.Timedelta('2H'))
Run Code Online (Sandbox Code Playgroud)

但我收到了一个错误,如 AttributeError: 'DatetimeProperties' object has no attribute 'Timedelta'。

有人可以建议我正确的方法吗?

任何帮助,将不胜感激。

jez*_*ael 6

我想你需要groupby+ Grouper+一些聚合函数:

df = last8.groupby(pd.Grouper(freq='2H', key='Time')).mean()
Run Code Online (Sandbox Code Playgroud)

或resample+ 一些聚合函数:

df = last8.resample('2H', on='Time').mean()
Run Code Online (Sandbox Code Playgroud)

或使用groupby+ floor:

df = last8.groupby(last8.Time.dt.floor('2H')).mean()
Run Code Online (Sandbox Code Playgroud)
print (df)
                     T201FN1ST2010  T201FN1VT2010
Time                                             
2017-12-26 00:00:00     855.551667       0.866667
2017-12-26 02:00:00     855.878333       0.853333
2017-12-26 04:00:00     855.725000       0.856667
2017-12-26 06:00:00     854.930000       0.880000
Run Code Online (Sandbox Code Playgroud)