我的数据由一系列时间组成,每秒有10个数据点,每个时间对应一个强度值数组。所以,举一个例子,让我说我有:
times = np.arange(0,100,0.1)
intensities = np.random.rand(len(times))
如果我使用更长的平均时间,我想看看数据会是什么样子,所以我想创建一些箱子,例如1秒,5秒和10秒,并平均这些新箱子中的强度值。 numpy中最好的方法是什么? (或者其他python包,但我假设numpy / scipy对我有用。)我可以使用for循环,但我希望有更好的方法。 谢谢!
答案 0 :(得分:5)
您可以使用stackoverflow here上提到的convolve
计算移动平均线。
from pylab import plot, show
import numpy as np
times = np.arange(0,100,0.1)
intensities = np.random.rand(len(times))
def window(size):
return np.ones(size)/float(size)
plot(times,intensities,'k.')
plot(times,np.convolve(intensities,window(10),'same'),'r')
plot(times,np.convolve(intensities,window(100),'same'),'b')
show()
答案 1 :(得分:4)
您可以重新整形数据,将其分组为10,50或100组。然后调用mean(axis=-1)
方法获取最后一个轴(大小为10,50或100的轴)的平均值:
使用此设置:
In [10]: import numpy as np
In [11]: times = np.linspace(0,100,1000)
In [12]: intensities = np.random.rand(len(times))
以下是每10个值的方法:
In [13]: intensities.reshape(-1,10).mean(axis=-1)
Out[13]: <output omitted due to length>
每50个值的含义:
In [14]: intensities.reshape(-1,50).mean(axis=-1)
Out[14]: <output omitted due to length>
表示每100个值:
In [15]: intensities.reshape(-1,100).mean(axis=-1)
Out[15]:
array([ 0.50969463, 0.5095131 , 0.52503152, 0.49567742, 0.52701341,
0.53584475, 0.54808964, 0.47564486, 0.490907 , 0.50293636])
arr.reshape(-1, 10)
告诉NumPy重新整形数组arr
,使其在最后一个轴上具有大小为10的形状。 -1
告诉NumPy给第一个轴提供填充数组所需的大小。
请注意,以这种方式使用reshape
要求len(intensities)
可以被您要分组的大小(例如10,50,100)整除。