如果您有兴趣,请使用以下解决方法。
df = pd.DataFrame({'A' : np.arange(10),
'B' : np.arange(10,20)},
index=[1,2,3,5,8,9,11,14,19,20])
def var_window(df, size, min_periods=None):
"""Operates on the index."""
result = []
df = df.sort_index()
for i in df.index:
start = i - size + 1
res = df.loc[start:i].sum().tolist()
result.append(res)
result = pd.DataFrame(result, index=df.index)
if min_periods:
result.loc[:min_periods - 1] = np.nan
return result
print(var_window(df, size=3, min_periods=3, inclusive=True))
0 1
1 NaN NaN
2 NaN NaN
3 3.0 33.0
5 5.0 25.0
8 4.0 14.0
9 9.0 29.0
11 11.0 31.0
14 7.0 17.0
19 8.0 18.0
20 17.0 37.0
说明:通过索引循环。在每个值处,将DataFrame截断为尾部窗口大小。这里的'大小'不是一个计数,而是你定义的一个范围。
在上面的索引值为8时,您正在对索引为8,7或6(即> 8 - 3 + 1)的值A
进行求和。该范围内唯一的索引值是8,因此总和就是原始帧的值。相对而言,对于指数值11,总和将包括9和11的值(5 + 6 = 11,由此产生的总和为A
)。
这个比较标准的滚动OPS:
print(df.rolling(window=3).sum())
A B
1 NaN NaN
2 NaN NaN
3 3.0 33.0
5 6.0 36.0
8 9.0 39.0
9 12.0 42.0
11 15.0 45.0
14 18.0 48.0
19 21.0 51.0
20 24.0 54.0
如果我误解你的问题,让我知道如何。无可否认,它显着变慢了:
%timeit df.rolling(window=3).sum()
1000 loops, best of 3: 627 µs per loop
%timeit var_window(df, size=3, min_periods=3)
100 loops, best of 3: 3.59 ms per loop
你能提供一个数据的例子吗?你是指时间栏还是任何数字栏? – Vaishali
我要说不。 [根据文档](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html#pandas-dataframe-rolling)...“窗口:int或偏移量 大小这是用于计算统计的 的观测值的数量,每个窗口都是固定的大小。“ –