问题描述
我的工作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]
。是否有可能这样做吗?
>>>导入numpy的是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对于以s x如果X])在np.c_ [A,B,C]为S]
[167.33333333333334,157.33333333333334,553.0,507.5]
或者,也许一个更好的选择:
>>> A = np.vstack([A,B,C])
>>> np.average(A,轴= 0,权重= A.astype(布尔))
阵列([167.33333333,157.33333333,553,507.5])
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?
>>> 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 ])
这篇关于平均数目与numpy的阵列的不考虑零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!