Numpy - 计算一维数组的元素均值

发布于 01-09 10:35 字数 431 浏览 2 评论 0原文

我发现了多个标题相似的问题,但它们与我的案例不匹配。

我有一个带有偏移值的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不咬妳我踢妳2025-01-16 10:35:52

您可以使用累积和 (np.cumsum) 并除以所见元素的数量(使用 np.arange):

a = np.array([2, 4, 5, 7, 8, 10])
out = np.cumsum(a)/(np.arange(a.shape[0])+1)

输出:

array([2.        , 3.        , 3.66666667, 4.5       , 5.2       ,
       6.        ])

You can use the cumulated sum (np.cumsum) and divide by the number of seen elements (using np.arange):

a = np.array([2, 4, 5, 7, 8, 10])
out = np.cumsum(a)/(np.arange(a.shape[0])+1)

output:

array([2.        , 3.        , 3.66666667, 4.5       , 5.2       ,
       6.        ])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文