熊猫找到每小时滚动平均值

时间:2019-07-16 02:20:07

标签: python-3.x pandas dataframe datetime python-datetime

我的数据集df如下所示。这是一个基于minute的数据集。

time, Open, High
2017-01-01 00:00:00, 1.2432, 1.1234
2017-01-01 00:01:00, 1.2432, 1.1234
2017-01-01 00:02:00, 1.2332, 1.1234
2017-01-01 00:03:00, 1.2132, 1.1234
...., ...., ....
2017-12-31 23:59:00, 1.2132, 1.1234

我想为rolling mean列找到每小时的Open,但是它应该很灵活,以便我也可以为其他列找到每小时的rolling mean

我做了什么?

我能够找到如下所示的daily rolling average

# Pandas code to find the rolling mean for a single day

df
.assign(1davg=df.rolling(window=1*24*60)['Open'].mean()) 
.groupby(df['time'].dt.date) 
.last() 

请注意,将这行代码从{window=1*24*60更改为window=60)无效,因为我已经尝试过了。

新的output应该如下所示:

time,                 Open,  High,   Open_hour_avg
2017-01-01 00:00:00, 1.2432, 1.1234,   1.2532
2017-01-01 01:00:00, 1.2432, 1.1234,   1.2632    
2017-01-01 02:00:00, 1.2332, 1.1234,   1.2332
2017-01-01 03:00:00, 1.2132, 1.1234,   1.2432
...., ...., ...., ....
2017-12-31 23:00:00, 1.2132, 1.1234,   1.2232

在这里

2017-01-01 00:00:00, 1.2432, 1.1234, 1.2532minute的{​​{1}}平均值

midnight2017-01-01 01:00:00, 1.2432, 1.1234, 1.2632的{​​{1}}平均值

2 个答案:

答案 0 :(得分:1)

我们可以做到

df['open_ave_hour']=df.groupby(df.time.dt.strftime('%H:%M:%S')).Open.mean().reindex(df.time.dt.strftime('%H:%M:%S')).to_numpy()

或变换

df['open_ave_hour']=df.groupby(df.time.dt.strftime('%H:%M:%S')).Open.transform('mean')

答案 1 :(得分:0)

这就是我的工作方式:

import pandas as pd

# After your CSV data is in a df

df['time'] = pd.to_datetime(df['time'])
df.index = df['time']
df_mean = df.resample('H').mean()


time,                 Open       High   
2017-01-01 00:00:00 1.051488    1.051500     
2017-01-01 01:00:00 1.051247    1.051275     
2017-01-01 02:00:00 1.051890    1.051957     
2017-01-01 03:00:00 1.051225    1.051290     
...., ...., ....
2017-12-31 23:00:00 1.051225    1.051290