如何计算列表中的值的平均值,省略特殊值(-999)?
import numpy as np
A = [4,5,7,8,-999]
M = np.mean(A)
任何想法???
答案 0 :(得分:3)
>>> import numpy as np
>>> a = np.array([1,2,3,4,5])
>>> np.mean(a)
3.0
>>> np.mean(a[a<=3])
2.0
>>> np.mean(a[a!=4])
2.75
对于OP案例:
np.mean(A[A!=-999])
<强>性能强>
让我们测试三个片段:普通np.mean
,masked_array
和使用Python生成器的“天真”解决方案。数组有1000000个值。
from timeit import timeit
setup = 'import numpy as np; a=np.arange(0, 1000000)'
snippets = [
'assert np.mean(a[a!=999999]) == 499999.0',
'm=np.ma.masked_array(a,a==999999); assert np.ma.mean(m) == 499999.0',
'assert sum(x for x in a if x != 999999)/999999 == 499999'
]
timings = [timeit(x, setup=setup, number=10) for x in snippets]
print('\n'.join(str(x) for x in timings))
结果:
0.0840559005737
0.0890350341797
10.4104599953
普通np.mean
和masked_array
有接近的时间,而“天真”解决方案的速度要慢100多倍。
答案 1 :(得分:3)
在numpy中你可以使用蒙面数组的意思:
import numpy as np
A = np.array([4,5,7,8,-999])
mask_A = A == -999
ma_A = np.ma.masked_array(A, mask_A)
print np.ma.mean(ma_A)
结果:
6.0
答案 2 :(得分:1)
我不知道numpy。但这将有效
A = [4,5,7,8,-999]
A = [item for item in A if item != -999]
print sum(A)/float(len(A))
<强>输出强>
6.0
修改强>
要查找所有子列表的方法,
A = [[4,5,7,8,-999],[3,8,5,7,-999]]
M = [sum(z)/float(len(z)) for z in [[x for x in y if x != -999] for y in A]]
print M
<强>输出强>
[6.0, 5.75]
答案 3 :(得分:0)
from numpy import*
A = [4,5,7,8,-999]
result = mean(A[A!=-999])
print (result)