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

Question:

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) ?

Asked By: Wenjie Yu

||

Answers:

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]]
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.