如何平均取一个数据帧中的三行,并将第一行的索引分配给均值?

时间:2018-07-02 11:36:16

标签: python pandas dataframe

我有一个时间戳为5分钟的数据框,我想切换为15分钟。因此,我想取3个5分钟周期的平均值,然后将第一个周期的索引值分配给该平均值,以建立另一个数据帧。

df1= 
                                    variable_1
(Settlement_Date,)                                
2018-06-30 20:30:00                     4.5
2018-06-30 20:35:00                     3.8
2018-06-30 20:40:00                     4.2
2018-06-30 20:45:00                     4.1
2018-06-30 20:50:00                     6.0
2018-06-30 20:55:00                     3.3
2018-06-30 21:00:00                     1.9
2018-06-30 21:05:00                     2.8
2018-06-30 21:10:00                     3.1
...                                     ... 

我希望这个数据框变成这样的东西

df1= 
                                    variable_1
(Settlement_Date,)                                
2018-06-30 20:30:00                     4.2
2018-06-30 20:45:00                     4.5
2018-06-30 21:00:00                     2.6 
...                                     ... 

我尝试使用“ for循环”,但是在将日期重新返回到数据框中时遇到问题

mean_list = []
date_list = []

for i in range(len(df1)-3):
    mean_holding = df1[:i+3].mean()
    date_holding = df1.iloc[i+3]
    mean_list.append(mean_holding)
    date_list.append(date_holding)

1 个答案:

答案 0 :(得分:1)

我认为需要resamplemean

df = df.resample('15Min').mean()

使用Grouper的替代解决方案:

df = df.groupby(pd.Grouper(freq='15Min')).mean()

print (df)
                     variable_1
(Settlement_Date,)             
2018-06-30 20:30:00    4.166667
2018-06-30 20:45:00    4.466667
2018-06-30 21:00:00    2.600000