How to use df. rolling (..., win type= 'exponential'). mean()
I want to calculate a weighted moving average using df.rolling().mean()
. The weights for the values in the window can be set using the win_type
parameter. Some parameter values (read more here), also require the input of an additional argument.
# здесь дополнительный аргумент std в методе .mean()
df.rolling(window=21, min_periods=10, win_type='gaussian').mean(std=1)
# работает
But when it comes to win_type='exponential'
`df.rolling(window=21, min_periods=10, win_type='exponential').mean(tau=10)
# ValueError: The 'exponential' window needs one or more parameters -- pass a tuple.
Can you tell me how to use the exponentially weighted moving average win_type='exponential
correctly?
UPD: Added df
Dan Seth a
a = pd.DataFrame([[1, 20, 1], [2, 22, 1], [3, 23, 0], [1, 19, 1], [2, 24, 0],
[2, 21, 1], [1, 17, 1], [2, 29, 0], [2, 27, 0]],
columns=['type', 'size', 'target'])
All conversions except win_type='exponential'
work
a = a.assign(rolling_col=a.groupby(['type'])['size'].transform(
lambda x: x.rolling(2, min_periods=1, win_type='gaussian').mean(std=0.1)))
Will give the output
type size target rolling_col
1 20 1 20.0 # В данному примере rolling_col рассчитан при помощи win_type='gaussian'
2 22 1 22.0 # a должен быть рассчитан при win_type='exponential'
3 23 0 23.0
1 19 1 19.5
2 24 0 23.0
2 21 1 22.5
1 17 1 18.0
2 29 0 25.0
2 27 0 28.0
Does not work with win_type='exponential'
, outputs:
# ValueError: The 'exponential' window needs one or more parameters -- pass a tuple.
2
1 answers
After a little experimenting and carefully rereading the error message, I came to this option:
In [14]: a.assign(rolling_col=
...: a.groupby(['type'])[['size']].transform(
...: lambda x: x.rolling(window=(2,10), min_periods=1, win_type='exponential').mean(std=0.1)))
Out[14]:
type size target rolling_col
0 1 20 1 20.000000
1 2 22 1 22.000000
2 3 23 0 23.000000
3 1 19 1 19.166667
4 2 24 0 23.666667
5 2 21 1 21.500000
6 1 17 1 17.333333
7 2 29 0 27.666667
8 2 27 0 27.333333
NOTE: note the window=(2,10)
parameter, where the second element of the tuple is the value tau
.
PS from the official documentation:
win_types
- exponential (needs
tau
), center is set to None.
3
Author: MaxU, 2019-08-27 16:30:25