我试图计算一些不完整数据的滚动平均值。我想在大小为第1列(英里)值1.0的窗口中平均第2列中的值。我已经尝试了.rolling(),但是(根据我有限的理解),这只会基于索引而不是列值创建窗口
import pandas as pd
import numpy as np
df = pd.DataFrame([
[4.5, 10],
[4.6, 11],
[4.8, 9],
[5.5, 6],
[5.6, 6],
[8.1, 10],
[8.2, 13]
])
averages = []
for index in range(len(df)):
nearby = df.loc[np.abs(df[0] - df.loc[index][0]) <= 0.5]
averages.append(nearby[1].mean())
df['rollingAve'] = averages
提供所需的输出:
0 1 rollingAve
0 4.5 10 10.0
1 4.6 11 10.0
2 4.8 9 10.0
3 5.5 6 6.0
4 5.6 6 6.0
5 8.1 10 11.5
6 8.2 13 11.5
但对于大数据帧来说,这会大大降低速度。有没有一种方法可以实现具有不同窗口大小的.rolling()或类似的功能
如果索引类型为
DateTimeIndex
或TimedeltaIndex
,则df.rolling
和series.rolling
允许基于值的窗口。您可以使用此选项接近所需的结果:输出:
优势 这是一个三线解决方案,应具有良好的性能,充分利用datetime后端
缺点 这绝对是一个错误,将英里列转换为时间增量秒,并且平均值不居中(
center
不适用于datetimelike和基于偏移量的窗口)总的来说:如果你重视绩效,并且能够接受一种不以中心为中心的方式,那么这将是一个很好的评论方式
熊猫的BaseIndexer非常方便,尽管需要一点挠头才能弄对
在下面,我使用np.searchsorted快速查找每个窗口的索引(开始,结束):
一些高级选项:
min_periods
、center
和closed
是根据DataFrame.rolling指定的内容实现的应用程序:
计时:
性能更新:
在@anon01发表评论后,我想知道如果滚动涉及到大窗口,是否可以加快速度。原来我应该先测量熊猫的滚动平均值和总和表现。。。(过早优化,有人吗?)
无论如何,我们的想法是只做一次
cumsum
,然后取windows端点所解引用的元素的差异:有了这个(以及上面的100万行),我看到:
与:
然而<熊猫可能已经在做这样的优化了(这是一个非常明显的优化)。时间不会随着窗口的增大而增加(这就是为什么我说我应该先检查)
相关问题 更多 >
编程相关推荐