没有考虑零值的numpy数组的平均值

时间:2012-11-08 03:21:26

标签: python arrays numpy average

我正在研究numpy,我有许多具有相同大小和形状的数组,如: a= [153 186 0 258] b=[156 136 156 0] c=[193 150 950 757] 我想要平均数组,但我希望程序忽略计算中的零值。因此,此示例的结果数组将为:d=[167.333 157.333 553 507.5] 这是这个计算的结果:d=[(153+156+193)/3 (186+136+150)/3 (156+950)/2 (258+757)/2]。有可能吗?

1 个答案:

答案 0 :(得分:12)

>>> import numpy as np
>>> a = np.array([153, 186, 0, 258])
>>> b = np.array([156, 136, 156, 0])
>>> c = np.array([193, 150, 950, 757])
>>> [np.mean([x for x in s if x]) for s in np.c_[a, b, c]]
[167.33333333333334, 157.33333333333334, 553.0, 507.5]

或许是一个更好的选择:

>>> A = np.vstack([a,b,c])
>>> np.average(A, axis=0, weights=A.astype(bool))
array([ 167.33333333,  157.33333333,  553.        ,  507.5       ])