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,510 points
8,149 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
• 58,020 points

Related Questions In Python

+1 vote
7 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 23, 2018 in Python by charlie_brown
• 7,720 points
923 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
• 58,020 points
11,770 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,300 points
927 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
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
• 58,020 points
1,166 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
• 58,020 points
24,272 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP