【发布时间】:2018-05-05 04:07:30
【问题描述】:
我有一个函数 f,我想在滑动窗口中高效地计算它。
def efficient_f(x):
# do stuff
wSize=50
return another_f(rolling_window_using_strides(x, wSize), -1)
我在 SO 上看到使用 strides 特别有效: 从 numpy.lib.stride_tricks 导入 as_strided
def rolling_window_using_strides(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
print np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides).shape
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
然后我尝试将其应用于 df:
df=pd.DataFrame(data=np.random.rand(180000,1),columns=['foo'])
df['bar']=df[['foo']].apply(efficient_f,raw=True)
# note the double [[, otherwise pd.Series.apply
# (not accepting raw, and axis kwargs) will be called instead of pd.DataFrame.
它运行得非常好,并且确实带来了显着的性能提升。 但是,我仍然收到以下错误:
ValueError: Shape of passed values is (1, 179951), indices imply (1, 180000).
这是因为我使用的是 wSize=50,这会产生
rolling_window_using_strides(df['foo'].values,50).shape
(1L, 179951L, 50L)
有没有办法通过零/np.nan 在边界处填充来获得
(1L, 180000, 50L)
因此与原始向量大小相同
【问题讨论】:
-
垫在末尾还是开始?
-
不确定默认情况下它的行为如何......我猜在开始时
标签: python pandas numpy sliding-window