positives = [b for b in A if b >= 0]
不做你认为它做的事。b
将是 7 个元素的列表,7 个元素的列表如何大于 0?
numpy 使这很容易:
import numpy as np
import numpy.ma as ma
A = [[-9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0],
[-9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0],
[0.040896, 0.018690, 0.005620, -9999.0, 0.038722, 0.018323, -9999.0],
[0.039443, 0.017517, 0.003460, -9999.0, 0.035526, 0.011692, -9999.0],
[-9999.0, 0.017963, 0.005264, -9999.0, 0.03788, 0.014316, -9999.0]]
A = np.array(A)
sigmas = []
for b in A:
bmask=ma.masked_array(b,mask=np.greater_equal(b,0))
b=b[bmask.mask]
print b
sigmas.append(np.std(b))
给
[]
[]
[ 0.040896 0.01869 0.00562 0.038722 0.018323]
[ 0.039443 0.017517 0.00346 0.035526 0.011692]
[ 0.017963 0.005264 0.03788 0.014316]
>>> sigmas
[0.0, 0.0, 0.013412289355661845, 0.013828802328473713, 0.011917047544903896]
编辑:回应评论
>>> A=[[1,2,3,4,5,6,7],[2,-3,4,-3,2,1,-9]]
>>> [b for b in A if b>=0]
[[1, 2, 3, 4, 5, 6, 7], [2, -3, 4, -3, 2, 1, -9]]
Python 不会给你一个错误,但它不会比较b
to中的元素0
,它只是比较b
,它被评估为布尔值。
在这里,您可以清楚地看到正在发生的事情:
>>> bool(b)
True
>>> True >= 0
True
对于 A 中的每个 7 个数字列表,b
您只是在做True >= 0
,总是如此True
。
编辑2:我是个白痴,现在看到您正在尝试使用地图,而我正在谈论的问题将被避免。只需更改G = map(sigma, zip(*A))
为G = map(sigma, A)
edit3: : 你返回i
而不是diff
. 这是代码:
def sigma(A):
positives = [b for b in A if b >= 0]
if positives:
mean = sum(positives) / len(positives)
diff = ((sum([abs(i - mean)**2 for i in positives]))/(len(positives)))**(0.5)
for i in positives:
if (abs(i - mean)) > (diff*3):
return -9999.00
return diff
else:
return -9999.00
A = [[-9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0],
[-9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0],
[0.040896, 0.018690, 0.005620, -9999.0, 0.038722, 0.018323, -9999.0],
[0.039443, 0.017517, 0.003460, -9999.0, 0.035526, 0.011692, -9999.0],
[-9999.0, 0.017963, 0.005264, -9999.0, 0.03788, 0.014316, -9999.0]]
G = map(sigma, A)
这使:
>>> G
[-9999.0, -9999.0, 0.013412289355661845, 0.013828802328473713, 0.011917047544903896]
编辑4:澄清的问题
def sigma(A):
positives = [b for b in A if b >= 0]
sq_err=[]
if positives:
mean = sum(positives) / len(positives)
diff = ((sum([abs(i - mean)**2 for i in positives]))/(len(positives)))**(0.5)
for i in positives:
if (abs(i - mean)) > (diff*3):
sq_err.append(-9999.00)
else:
sq_err.append(i)
else:
return [-9999.00]
return sq_err
A = [[-9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0],
[-9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0, -9999.0],
[0.040896, 0.018690, 0.005620, -9999.0, 0.038722, 0.018323, -9999.0],
[0.039443, 0.017517, 0.003460, -9999.0, 0.035526, 0.011692, -9999.0],
[-9999.0, 0.017963, 0.005264, -9999.0, 0.03788, 0.014316, -9999.0]]
G = map(sigma, A)
给
>>> G
[[-9999.0], [-9999.0], [0.040896, 0.01869, 0.00562, 0.038722, 0.018323], [0.039443, 0.017517, 0.00346, 0.035526, 0.011692], [0.017963, 0.005264, 0.03788, 0.014316]]