在numpy中有一种快速计算多轴平均值的方法吗?我正在计算除n维数组的0轴以外的所有平均值。
我目前正在这样做;
for i in range(d.ndim - 1):
d = d.mean(axis=1)
我想知道是否有一个不使用python循环的解决方案。
答案 0 :(得分:30)
在numpy 1.7中,您可以将多个轴赋予np.mean
:
d.mean(axis=tuple(range(1, d.ndim)))
我猜这将与其他提议的解决方案类似地执行,除非重新整形数组以展平所有维度触发数据的副本,在这种情况下,这应该更快。所以这可能会带来更稳定的表现。
答案 1 :(得分:8)
我的方法是重新整形数组以展平所有更高的尺寸,然后在轴1上运行均值。这是你想要的吗?
In [14]: x = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
In [16]: x.reshape((x.shape[0], -1)).mean(axis=1)
Out[16]: array([ 2.5, 6.5])
(步骤2只计算较高dims长度的乘积)
答案 2 :(得分:3)
您也可以使用numpy.apply_over_axes:
import numpy as np
x = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])
y = np.apply_over_axes(np.mean, x, (1, 2))
y = array([[[ 2.5]],[[ 6.5]]])
答案 3 :(得分:0)
根据@ dsg101的建议,这是你想要的那种吗?
>>> import numpy as np
>>> d=np.reshape(np.arange(5*4*3),[5,4,3])
>>> d
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]],
[[24, 25, 26],
[27, 28, 29],
[30, 31, 32],
[33, 34, 35]],
[[36, 37, 38],
[39, 40, 41],
[42, 43, 44],
[45, 46, 47]],
[[48, 49, 50],
[51, 52, 53],
[54, 55, 56],
[57, 58, 59]]])
>>> np.mean(np.reshape(d,[d.shape[0],np.product(d.shape[1:])]),axis=1)
array([ 5.5, 17.5, 29.5, 41.5, 53.5])