Replace NaN in rolling mean in python

0 votes

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?

Sep 27, 2018 in Python by bug_seeker
• 15,350 points
682 views

1 answer to this question.

0 votes

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
answered Sep 27, 2018 by Priyaj
• 56,520 points

Related Questions In Python

+1 vote
3 answers
0 votes
1 answer

What does ' -> ' mean in Python function definitions?

It's a function annotation. In more detail, Python 2.x ...READ MORE

answered May 22, 2018 in Python by charlie_brown
• 7,720 points
54 views
0 votes
1 answer

How to replace values with None in Pandas data frame in Python?

Actually in later versions of pandas this ...READ MORE

answered Aug 30, 2018 in Python by Priyaj
• 56,520 points
1,216 views
0 votes
1 answer

.replace() regex in Python

No,  .replace() does not support regex. Regular expressions ...READ MORE

answered Nov 26, 2018 in Python by SDeb
• 13,160 points
65 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 229 views
0 votes
1 answer

How to use string.replace() in python 3.x

replace() is a method of <class 'str'> ...READ MORE

answered Aug 3, 2018 in Python by Priyaj
• 56,520 points
57 views
0 votes
1 answer

How can I check for NaN in Python?

math.isnan() Checks if the float x is a ...READ MORE

answered Aug 16, 2018 in Python by Priyaj
• 56,520 points
6,645 views