我想在具有日期索引的 DataFrame 上应用偏移滚动窗口函数。这是一个例子:
rng = pd.date_range('2017-01-03', periods=20, freq='W')
df = pd.DataFrame(np.random.randn(20), rng, columns=['Val'])
df.index.name = 'Date'
r = df.rolling('15D')
这会产生一个 DataFrame df
,如:
Val
Date
2017-01-08 0.592210
2017-01-15 -1.243938
2017-01-22 -0.713988
2017-01-29 1.554777
...
但我无法弄清楚如何在我应用于Rolling
窗口的任何函数中查看与每个 Val 关联的日期。例如,以下内容:
def f(data=None): # I really want to reference the Date associated with each Val in here!
print('f(%s) data=%s' % (str(type(data)), data))
return 1
r.apply(lambda x: f(x))
表明我所看到的只是ndarray
每次通话的一个:
f(<class 'numpy.ndarray'>) data=[0.59220959]
f(<class 'numpy.ndarray'>) data=[ 0.59220959 -1.24393841]
f(<class 'numpy.ndarray'>) data=[ 0.59220959 -1.24393841 -0.71398767]
f(<class 'numpy.ndarray'>) data=[-1.24393841 -0.71398767 1.55477737]
...
有没有办法以聚合函数看到与窗口中每个值关联的索引的方式在 DataFrame 上调用时间偏移滚动窗口?
例如,这样我就可以应用一个看起来像这样的函数:
f(<class 'DataFrame'>) data=[{2017-01-08, 0.59221}]
f(<class 'DataFrame'>) data=[{2017-01-08, 0.59221}, {2017-01-15, -1.243938}]
...