如何加快熊猫系列的"decay"填充功能?



我想加快我的"衰减"前向填充函数的以下实现,该函数用最后一个非零值乘以衰减因子alpha ** (t-T)填充零值,其中0<alpha<1(t-T)是与最后一个非零值的距离:

def decay_series(s):
decay_fac = 0.9
for i in range(1, len(s)):
if abs(s.iloc[i]) < 1e-6:
s.iloc[i] = s.iloc[i - 1] * decay_fac
return s
s = pd.Series([0,0, 1, 2, 0,0,1,0,0,1])
s
Out[24]: 
0    0
1    0
2    1
3    2
4    0
5    0
6    1
7    0
8    0
9    1
dtype: int64
decay_series(s)
Out[25]: 
0    0.00
1    0.00
2    1.00
3    2.00
4    1.80
5    1.62
6    1.00
7    0.90
8    0.81
9    1.00
dtype: float64

然而,由于使用了纯python for loop,这太慢了。有没有办法加快速度,例如,通过一些巧妙地应用pandas的原生组件?不幸的是,似乎fillnareplace方法不支持要应用的自定义用户方法。

使用mask和广播

(s.mask(s.eq(0)).ffill() * decay_fac ** s.groupby(s.ne(0).cumsum()).cumcount()).fillna(0)
<小时 />
0    0.00
1    0.00
2    1.00
3    2.00
4    1.80
5    1.62
6    1.00
7    0.90
8    0.81
9    1.00
dtype: float64

timings

9.62 毫秒与 10000 行的 1.12 秒

%timeit (s.mask(s.eq(0)).ffill() * 0.9 ** s.groupby(s.ne(0).cumsum()).cumcount()).fillna(0)
9.62 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit decay_series(s)
1.12 s ± 161 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

最新更新