我需要该小时内所有值的均值,并且每天需要在所有这些小时中使用它。
例如:
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。
我尝试使用此answer解决问题,但是它不起作用。 谁能帮我?
答案 0 :(得分:1)
尝试groupby
,dt.hour
,mean
,reset_index
和assign
:
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
答案 1 :(得分:1)
resample
中的 pandas
应该适合您的情况
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