Reputation: 83
I would like to understand how to replace this simple while loop with less characters.
a:
2017-12-31 10
2018-1-1 9
2018-1-2 15
2018-1-3 25
2018-1-4 30
I would like to replace this code with a shorter code:
b=pd.Series(index=a.index)
b[0]=0
i=1
while i< len(b):
b[i]=a[i]*0.1+b[i-1]*0.9
i+=1
Upvotes: 1
Views: 148
Reputation: 294508
Setup
It's always best to provide a definitive way to reconstruct your data. With this code, others can play with it to figure out stuff.
a = pd.Series(
[10, 9, 15, 25, 30],
pd.date_range('2017-12-31', periods=5)
)
Solution
Use Pandas' pd.Series.ewm
method with an alpha
parameter set to .9
a.ewm(alpha=.9).mean()
2017-12-31 10.000000
2018-01-01 9.090909
2018-01-02 14.414414
2018-01-03 23.942394
2018-01-04 29.394294
Freq: D, dtype: float64
To more closely match what your code does, use the adjust=False
option with alpha=.1
a.ewm(alpha=.1, adjust=False).mean()
2017-12-31 10.0000
2018-01-01 9.9000
2018-01-02 10.4100
2018-01-03 11.8690
2018-01-04 13.6821
Freq: D, dtype: float64
Upvotes: 2