我有一个带有时间戳列/索引的数据框,我正在计算过去5秒钟的移动平均值。
数据看起来像这样:
例如:在索引5处,过去5秒钟的平均值为56.5541。我需要计算接下来5秒钟的平均值,不包括当前时间,即索引6、7、8(56.545)。
使用df.index.get_indexer()函数,我能够提取要包含在平均值中的最后一行的索引。
df['Mid-Price'].rolling(window=time_diff, min_periods=1, closed='both').mean()
到目前为止一切顺利。
现在我还需要计算接下来5秒钟的移动平均值。然而,我的时间戳不是均匀分布的,因此我不能只是将数据框移位以重新计算第二个平均值。数据看起来像这样:
Timestamp Price Start Stop
0, 2019-01-02 08:30:00, 56.565, 0, 5
1, 2019-01-02 08:30:01, 56.565, 1, 6
2, 2019-01-02 08:30:02, 56.565, 2, 6
3, 2019-01-02 08:30:03, 56.540, 3, 7
4, 2019-01-02 08:30:04, 56.545, 4, 7
5, 2019-01-02 08:30:05, 56.545, 5, 8
6, 2019-01-02 08:30:07, 56.540, 6, 10
7, 2019-01-02 08:30:09, 56.550, 7, 12
8, 2019-01-02 08:30:10, 56.545, 8, 12
9, 2019-01-02 08:30:11, 56.550, 9, 12
10,2019-01-02 08:30:12, 56.570, 10, 13
例如:在索引5处,过去5秒钟的平均值为56.5541。我需要计算接下来5秒钟的平均值,不包括当前时间,即索引6、7、8(56.545)。
使用df.index.get_indexer()函数,我能够提取要包含在平均值中的最后一行的索引。
df['stop'] = df.index.get_indexer(df['Date-Time-Exch'] + time_diff, method='bfill')
我希望能够以类似于iloc切片的方式使用“start”和“stop”中的值
df.iloc[df['start']:df['stop'], 1].mean()
但这并不起作用。
或者,我想到了这个:
def get_indexes(time_index, offset):
start, end = df.index.get_indexer([time_index, time_index + offset], method='bfill')
avg = df.iloc[start + 1:end + 1, 1].mean()
return avg
使用.apply()方法的速度太慢,无法发挥作用。
希望你能帮助我,因为我已经卡在这个问题上有一段时间了。