将一小时内的每个值分组为一个值,即平均值



我需要该小时内所有值的平均值,并且我需要每天对所有此类小时进行此操作。

例如:

Date                    Col1
2016-01-01 07:00:00      1
2016-01-01 07:05:00      2
2016-01-01 07:17:00      3
2016-01-01 08:13:00      2
2016-01-01 08:55:00      10
.
.
.
.
.
.
.
.
2016-12-31 22:00:00      3
2016-12-31 22:05:00      3
2016-12-31 23:13:00      4
2016-12-31 23:33:00      5
2016-12-31 23:53:00      6

因此,我需要将该日期内该小时内的所有值分组为一个(这是平均值(。

预期输出:

Date                    Col1
2016-01-01 07:00:00      2           ##(2016-01-01 07:00:00, 07:05:00, 07:17:00) 3 values falls between the one hour range for that date i.e. 2016-01-01 07:00:00 - 2016-01-01 07:59:00, both inclusive.
2016-01-01 08:00:00      6
.
.
.
.
.
.
.
.
2016-12-31 22:00:00      3
2016-12-31 23:00:00      5

因此,如果我一整年都这样做,那么最终总行数将是 365*24。

我尝试使用此答案解决,但它不起作用。谁能帮我?

pandasresample应该适合您的情况

import pandas as pd
df = pd.DataFrame({
    'Date':['2016-01-01 07:00:00','2016-01-01 07:05:00',
            '2016-01-01 07:17:00' ,'2016-01-01 08:13:00',
            '2016-01-01 08:55:00','2016-12-31 22:00:00',
            '2016-12-31 22:05:00','2016-12-31 23:13:00',
            '2016-12-31 23:33:00','2016-12-31 23:53:00'],
    'Col1':[1, 2, 3, 2, 10, 3, 3, 4, 5, 6]
})
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') # Convert series to datetime type
df.set_index('Date', inplace=True) # Set Date column as index

# for every hour, take the mean for the remaining columns of the dataframe 
# (in this case only for Col1, fill the NaN with 0 and reset the index)
df.resample('H').mean().fillna(0).reset_index()
df.head()
    Date    Col1
0   2016-01-01 07:00:00 2.0
1   2016-01-01 08:00:00 6.0
2   2016-01-01 09:00:00 0.0
3   2016-01-01 10:00:00 0.0
4   2016-01-01 11:00:00 0.0

尝试groupbydt.hourmeanreset_indexassign

print(df.groupby(df['Date'].dt.hour)['Col1'].mean().reset_index().assign(Date=df['Date']))

前两行的输出:

                 Date  Col1
0 2016-01-01 07:00:00     2
1 2016-01-01 07:05:00     6

最新更新