dhineshm
dhineshm

Reputation: 9

sum of past and future samples at each index in a list or array

I would like know is there any inbuilt python modules to calculate the average of current value, one past and one future value at every index in a list. (if past samples are not available, use only the future samples and vice versa)

If not, what is the efficient way to do that?

at index a(i), I need average(a(i-1), a(i), a(i+1))

for input:

[3, 5, 1, 6, 7]

I should get

[4, 3, 4, 4.6, 6.5]

Thanks in advance

Upvotes: 0

Views: 90

Answers (2)

Pavel
Pavel

Reputation: 7562

Oh, there are many different ways. Here's another:

x = np.array([3,5,1,6,7])
y = np.convolve(x, np.ones((3,))/3, mode='same')

# fixing the values at the boundaries
y[0]  = np.mean(x[:2])
y[-1] = np.mean(x[-2:])

It uses convolution to calculate an average of each 3 neighboring elements, but it pads zeros at the boundaries, so we need a second step to fix those.

Upvotes: 3

tobias_k
tobias_k

Reputation: 82939

You could use a list comprehension, getting the respective slice and it's mean.

>>> a = [3, 5, 1, 6, 7]
>>> [a[max(0, i-1):i+2] for i in range(len(a))]
[[3, 5], [3, 5, 1], [5, 1, 6], [1, 6, 7], [6, 7]]
>>> [np.mean(a[max(0, i-1):i+2]) for i in range(len(a))]
[4.0, 3.0, 4.0, 4.666666666666667, 6.5]

(Using max(0, i-1) here because [-1:2] would be an empty slice, but there might be a nicer way to achieve the same.)

Upvotes: 2

Related Questions