如何计算列表中的值的平均值,省略特殊值?

时间:2013-11-07 11:19:50

标签: python numpy

如何计算列表中的值的平均值,省略特殊值(-999)?

import numpy as np
A = [4,5,7,8,-999]
M = np.mean(A) 

任何想法???

4 个答案:

答案 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.meanmasked_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.meanmasked_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)