在 numpy 中获取 3D 数组的 2D 切片的平均值 [英] Get mean of 2D slice of a 3D array in numpy

查看:55
本文介绍了在 numpy 中获取 3D 数组的 2D 切片的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为的 numpy 数组:

(11L, 5L, 5L)

我想计算数组 [0, :, :], [1, :, :] 等的每个切片"的 25 个元素的平均值,返回 11 个值.

这看起来很傻,但我不知道如何做到这一点.我认为 mean(axis=x) 函数可以做到这一点,但我已经尝试了所有可能的轴组合,但没有一个给我想要的结果.

我显然可以使用 for 循环和切片来做到这一点,但肯定有更好的方法吗?

解决方案

对轴使用元组:

<预><代码>>>>a = np.arange(11*5*5).reshape(11,5,5)>>>a.mean(axis=(1,2))数组([ 12., 37., 62., 87., 112., 137., 162., 187., 212.,237., 262.])

这仅适用于 numpy 1.7+ 版.

I have a numpy array with a shape of:

(11L, 5L, 5L)

I want to calculate the mean over the 25 elements of each 'slice' of the array [0, :, :], [1, :, :] etc, returning 11 values.

It seems silly, but I can't work out how to do this. I've thought the mean(axis=x) function would do this, but I've tried all possible combinations of axis and none of them give me the result I want.

I can obviously do this using a for loop and slicing, but surely there is a better way?

解决方案

Use a tuple for axis :

>>> a = np.arange(11*5*5).reshape(11,5,5)
>>> a.mean(axis=(1,2))
array([  12.,   37.,   62.,   87.,  112.,  137.,  162.,  187.,  212.,
        237.,  262.])

Edit: This works only with numpy version 1.7+.

这篇关于在 numpy 中获取 3D 数组的 2D 切片的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆