Skip to main content
 首页 » 编程设计

python之在 pandas.Series 的大小为 k 的窗口中轻松找到每个第 n 个元素的平均值的方法 (不是滚动平均值)

2025年05月04日16rubylouvre

这里的动机是采用时间序列并获得整个子周期(天、周)的平均事件。

可以 reshape 数组并在 y 轴上取平均值来实现这一点,类似于这个答案(但使用 axis=2):

Averaging over every n elements of a numpy array

但我正在寻找可以处理长度为 N%k != 0 的数组的东西,并且不能通过用 1 或 0 reshape 和填充(例如 numpy.resize)来解决问题,即取现有的平均值仅数据。

例如,从长度为 N=10 且不能被 k=3 整除的序列 [2,2,3,2,2,3,2,2,3,6] 开始。我想要的是对尺寸不匹配的 reshape 数组的列取平均值:

在:[[2,2,3], [2,2,3], [2,2,3], [6]], k =3

输出:[3,2,3]

代替:

在:[[2,2,3], [2,2,3], [2,2,3], [6,0,0]], k =3

输出:[3,1.5,2.25]

谢谢。

请您参考如下方法:

您可以使用掩码数组填充特殊值,这些特殊值在求均值时会被忽略,而不是求和。

k = 3 
 
# how long the array needs to be to be divisible by 3 
padded_len = (len(in_arr) + (k - 1)) // k * k 
 
# create a np.ma.MaskedArray with padded entries masked 
padded = np.ma.empty(padded_len) 
padded[:len(in_arr)] = in_arr 
padded[len(in_arr):] = np.ma.masked 
 
# now we can treat it an array divisible by k: 
mean = padded.reshape((-1, k)).mean(axis=0) 
 
# if you need to remove the masked-ness 
assert not np.ma.is_masked(mean), "in_arr was too short to calculate all means" 
mean = mean.data