问题
I am working on numpy and I have a number of arrays with the same size and shape like:
a= [153 186 0 258]
b=[156 136 156 0]
c=[193 150 950 757]
I want to have average of the arrays, but I want the program to ignore the zero values in the computation. So, the resulting array for this example will be: d=[167.333 157.333 553 507.5]
this is the result of this computation: d=[(153+156+193)/3 (186+136+150)/3 (156+950)/2 (258+757)/2]
. Is it possible to do that?
回答1:
>>> 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]
Or maybe a nicer alternative:
>>> A = np.vstack([a,b,c])
>>> np.average(A, axis=0, weights=A.astype(bool))
array([ 167.33333333, 157.33333333, 553. , 507.5 ])
来源:https://stackoverflow.com/questions/13281904/average-of-a-number-of-arrays-with-numpy-without-considering-zero-values