Computing averages for a group of neighboring points in a line

92 views Asked by At

I am trying to compute the average for a group of neighboring points in an array that I can easily move around. I've been advised to define a vector called a "dither" of integers from for example, 5 to 15. Heres the code I have right now:

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

x = np.arange(0,10,.05)
wave = np.sin(x)

noise = np.random.normal(0,.05,200)
y = noise + wave
noise2 = np.random.normal(0,.05,200)
y2 = noise2 + wave
noise3 = np.random.normal(0,.05,200)
y3 = noise3 + wave


y_avg = (np.array(y) + np.array(y2) + np.array(y3)) / 3

for i in range(5, 15):
    mean = np.mean(y_avg)
print mean


plt.plot(x, y, color = 'red', label= 'line 1')
plt.plot(x, y2, color = 'pink', label = 'line 2')
plt.plot(x, y3, color = 'magenta', label = 'line 3')
plt.plot(x, y_avg, color = 'blue', label = 'average')
plt.legend()
plt.show()

Is there a better way to do this that involves indexing the data vector/how do I do that?

1

There are 1 answers

6
kezzos On BEST ANSWER

Use slicing of the vector:

mean = np.mean(y_avg[5:15])

If you want a mid point, this works for even sized windows:

def mean_slice(midp, size, array):
    slice_index = [midp - (size/2), midp + (size/2)]
    # Remove out of bounds indexes
    slice_index = [i if i > 0 else 0 for i in slice_index]
    slice_index = [i if i < len(array) else 0 for i in slice_index]
    return np.mean(array[slice(*slice_index)])

print mean_slice(1, 4, a)
>>>1.0