Numpy - 计算一维数组的元素均值
我发现了多个标题相似的问题,但它们与我的案例不匹配。
我有一个带有偏移值的 np.array ,我想要所有先前值的索引平均值。
我的第一个方法是使用 for 循环,但对于巨大的数组来说,这显然会减慢速度。
offset = np.array([2, 4, 5, 7, 8, 10])
mean_mraw = []
for i, ofs in enumerate(offset):
mean_mraw.append(offset[0:i+1].mean())
所以我期望的是:
mean_mraw = [2, 3, 3.6, 4.5, 5.2, 6] #np.array
是否有 np-build 函数来解决这个问题,或者我如何以另一种方式解决这个问题。
谢谢
I found multible questions with similar titles but they didn't match with my case.
I have a np.array with offset values and I want the mean value for index from all previous values.
My first approach was with a for loop, but with huge arrays it is obviously way to slow.
offset = np.array([2, 4, 5, 7, 8, 10])
mean_mraw = []
for i, ofs in enumerate(offset):
mean_mraw.append(offset[0:i+1].mean())
So what I expect is this:
mean_mraw = [2, 3, 3.6, 4.5, 5.2, 6] #np.array
Is there np- build in function for that or how could I solve that in another way.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以使用累积和 (
np.cumsum
) 并除以所见元素的数量(使用np.arange
):输出:
You can use the cumulated sum (
np.cumsum
) and divide by the number of seen elements (usingnp.arange
):output: