NumPy中多轴均值 [英] Mean over multiple axis in NumPy
问题描述
我想以Python的方式编写以下代码,在两个轴上应用均值.最好的方法是什么?
I Want to write the code below as Pythonic way, applying mean over two axis. What the best way to do this?
import numpy as np
m = np.random.rand(30, 10, 10)
m_mean = np.zeros((30, 1))
for j in range(30):
m_mean[j, 0] = m[j, :, :].mean()
推荐答案
如果您有足够新的NumPy,则可以
If you have a sufficiently recent NumPy, you can do
m_mean = m.mean(axis=(1, 2))
我不确定这是在1.7中引入的,尽管我不确定.该文档仅在1.10中进行了更新,以反映这一点,但它早于该版本.
I believe this was introduced in 1.7, though I'm not sure. The documentation was only updated to reflect this in 1.10, but it worked earlier than that.
如果您的NumPy年纪太大,则可以手动进行平均:
If your NumPy is too old, you can take the mean a bit more manually:
m_mean = m.sum(axis=2).sum(axis=1) / np.prod(m.shape[1:3])
这些都将产生一维结果.如果您确实想要那条额外的长度为1的轴,则可以执行m_mean = m_mean[:, np.newaxis]
之类的操作来将多余的轴放置在那里.
These will both produce 1-dimensional results. If you really want that extra length-1 axis, you can do something like m_mean = m_mean[:, np.newaxis]
to put the extra axis there.
这篇关于NumPy中多轴均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!