可以在多个维度上计算 numpy 数组的平均值,例如。my_ndarray.mean(axis=(1,2))
.
但是,它似乎不适用于掩码数组:
>>> import numpy as np
>>> a = np.random.randint(0, 10, (2, 2, 2))
>>> a
array([[[0, 9],
[2, 5]],
[[8, 6],
[0, 7]]])
>>> a.mean(axis=(1, 2))
array([ 4. , 5.25])
>>> ma = np.ma.array(a, mask=(a < 5))
>>> ma.mean(axis=(1, 2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/numpy/ma/core.py", line 5066, in mean
cnt = self.count(axis=axis)
File "/usr/lib/python2.7/site-packages/numpy/ma/core.py", line 4280, in count
n1 = np.size(m, axis)
File "/usr/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 2700, in size
return a.shape[axis]
TypeError: tuple indices must be integers, not tuple
如何计算多轴上掩码数组的平均值,最好与普通数组一样简单?
(我宁愿使用不暗示定义新功能的解决方案,如this answer中所建议的那样。)