Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the element of the output from the function pd.Series().rolling()?

I’m writing a simple function to calculate the moving average. For instance, if there is a list [1, 2, 3, 7, 9], then the moving average with the window size of 3, assuming the length of the output is the same, should be [nan, nan, 2, 4, 6.33]. I searched the web and found that ma = pd.Series(a).rolling(3).mean().tolist() can get the job done.

I guess what the rolling method did is generates a list [[nan], [nan], [1,2,3], [2,3,7],[3,7,9]]. But how can I get this list from the object generated by pd.Series(a).rolling(3) ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use list comprehension:

L = [list(x) for x in pd.Series(a).rolling(3)]
print (L)
[[1], [1, 2], [1, 2, 3], [2, 3, 7], [3, 7, 9]]

Missing values are possible with:

N = 3
L = [list(x) if i >= N else [np.nan] for i, x in enumerate(pd.Series(a).rolling(N),1)]
print (L)
[[nan], [nan], [1, 2, 3], [2, 3, 7], [3, 7, 9]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading