1

This is an extremely simple question, but extensive search has not provided me with a satisfactory answer.

I have an array of numbers that evolve "over time" e.g. x = [1, 2, 3, 4, 5] and I want to calculate the mean at each timepoint. With a for-loop I would simply do

import numpy as np

x = [1, 2, 3, 4, 5]
y = np.empty(5)

for i in range(5):

    y[i] = np.mean(x[0:i+1])

print(y)

[ 1.   1.5  2.   2.5  3. ]

In the processes I am working with, the numbers do not necessarily follow a simple dynamic like in the above. I wonder if there is some general way of applying a operation (such as calculating the mean) in a 'running' fashion, that is quicker than a for-loop?

1
  • 2
    "I wonder if there is some general way of applying a operation (such as calculating the mean) in a 'running' fashion, that is quicker than a for-loop?" Many numpy ufuncs have an accumulate method. Commented Apr 14, 2017 at 11:39

1 Answer 1

2

How about

a = np.array([1, 2, 3, 4, 5])
np.cumsum(a)/(np.arange(1, a.size + 1))

?

That will work for calculating a running average.

I wonder if there is some general way of applying a operation (such as calculating the mean) in a 'running' fashion

I can't provide an answer to this. It depends on the operation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.