Reputation: 790
Is there an elegant way or function to compute the mean of the last X elements of a list?
I have a list register
that increases in size at each iterations :
register = np.append(register, value)
I want to create another list in which an i
element corresponds to the mean of the X
last elements in register
register_mean[i] = np.mean(register[i-X:i])
The tricky part is for the first X
iterations, when there isn't X
values yet in register
. For these specific cases, I would like it to compute the mean on the firsts values of register
, and only take the first value of register
as first value of register_mean
.
This could be done during the iterations or after, when register
is complete.
I know there is lots of similar questions but haven't found one that answered this particular problem
Upvotes: 0
Views: 2128
Reputation: 410
If I understand your question correctly, this should do the work:
X = 4 # Span of mean
register_mean = [np.mean(register[max(i-X, 0): max(i-X, 0) + 1]) for i in range(len(register))]
It will essentially create a moving average of the register
elements between i - X
and i
; however, whenever i - X
is negative, it will only take the values between 0
and i + 1
.
Upvotes: 0
Reputation: 146
Could it be something as simple as
if X < i:
register_mean[i] = np.mean(register[:i])
This just averages however many prior points there are until you have enough to average X points
Perhaps I misinterpreted your intent!
Upvotes: 2