计算lin中一组相邻点的平均值

2024-04-24 23:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算数组中一组相邻点的平均值,我可以很容易地移动这些点。有人建议我定义一个称为“抖动”的向量,例如从5到15的整数。下面是我现在的代码:

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

有没有更好的方法来实现这一点,包括索引数据向量/我该怎么做


Tags: importplotnplinepltrandomwavemean
1条回答
网友
1楼 · 发布于 2024-04-24 23:25:56

使用矢量切片:

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

如果您想要一个中点,这适用于大小均匀的窗口:

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

相关问题 更多 >