首页 > 解决方案 > 将一小时内的每个值分组为一个值,这是它的平均值

问题描述

我需要该小时内所有值的平均值,并且我需要在每天的所有这些时间里都这样做。

例如:

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。

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

标签: pythonpandas

解决方案


resamplefrompandas应该适合你的情况

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

推荐阅读