Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing NaN in rolling mean(python)

I have a dataset as follows:

ts
Out[227]: 
       Sales
Month       
Jan     1808
Feb     1251
Mar     3023
Apr     4857
May     2506
Jun     2453
Jul     1180
Aug     4239
Sep     1759
Oct     2539
Nov     3923
Dec     2999

After taking a moving average of window=2, the output is:

shifted = ts.shift(0)

window = shifted.rolling(window=2)

means = window.mean()

print(means)
        Sales
Month        
Jan       NaN
Feb    1529.5
Mar    2137.0
Apr    3940.0
May    3681.5
Jun    2479.5
Jul    1816.5
Aug    2709.5
Sep    2999.0
Oct    2149.0
Nov    3231.0
Dec    3460.5

I want NaN to be replaced by its original value. Can it be done?

like image 317
IndigoChild Avatar asked Jun 20 '26 02:06

IndigoChild


1 Answers

Try this:

In [92]: ts.rolling(window=2, min_periods=1).mean()
Out[92]:
      Sales
Jan  1808.0
Feb  1529.5
Mar  2137.0
Apr  3940.0
May  3681.5
Jun  2479.5
Jul  1816.5
Aug  2709.5
Sep  2999.0
Oct  2149.0
Nov  3231.0
Dec  3461.0
like image 120
MaxU - stop WAR against UA Avatar answered Jun 22 '26 16:06

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!