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

f.a*_*uri 3 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].有可能吗?

wim*_*wim 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]
Run Code Online (Sandbox Code Playgroud)

或者更好的选择:

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