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,300 points
424 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,140 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,710 points
30 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,140 points
441 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
• 11,160 points
56 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
69 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,140 points
32 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,140 points
3,447 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.