How to get a mean array with numpy

ⅰ亾dé卋堺 提交于 2019-12-11 02:03:20

问题


I have a 4-D(d0,d1,d2,d3,d4) numpy array. I want to get a 2-D(d0,d1)mean array, Now my solution is as following:

area=d3*d4
mean = numpy.sum(numpy.sum(data, axis=3), axis=2) / area

But How can I use numpy.mean to get the mean array.


回答1:


You can reshape and then perform the average:

res = data.reshape(data.shape[0], data.shape[1], -1).mean(axis=2)

In NumPy 1.7.1 you can pass a tuple to the axis argument:

res = np.mean(data, axis=(2,3,4))



回答2:


In at least version 1.7.1, mean supports a tuple of axes for the axis parameter, though this feature isn't documented. I believe this is a case of outdated documentation rather than something you're not supposed to rely on, since similar routines such as sum document the same feature. Nevertheless, use at your own risk:

mean = data.mean(axis=(2, 3))

If you don't want to use undocumented features, you can just make two passes:

mean = data.mean(axis=3).mean(axis=2)


来源:https://stackoverflow.com/questions/18544396/how-to-get-a-mean-array-with-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!