2013-07-12 19 views
1

之前,我有這個程序讀入數據,平均橫跨三個一排,然後均線向下列,到目前爲止,它確實這一切的罰款。但是我現在想回去,並把它拿出負的數據點,我遇到了一些麻煩:篩選出陰性採取平均

from __future__ import division 
import csv 
v = open("Pt_2_Test_Data.csv", 'wb') #created file to write output to 
A =[] 
B = [] 
with open("test2.xls") as w: 
    w.next() # skip over header row 
    for row in w: 
     (date, time, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, 
     u, LZA, SZA, LAM) = row.split("\t") # split columns into fields 

     A.append([(float(a) + float(b) + float(c))/3, 
     (float(d) + float(e) + float(f))/3, 
     (float(g) + float(h) + float(i))/3, 
     (float(j) + float(k) + float(l))/3, 
     (float(m) + float(n) + float(o))/3, 
     (float(p) + float(q) + float(r))/3, 
     (float(s) + float(t) + float(u))/3]) 

def mean(B): 
     return sum(B)/len(B) 
for x in A: 
     if x > 0: 
       B.append(x) 

print B 
C = map(mean, zip(*B)) 
print C  

v.close() 

(我並不擔心將數據寫入該文件還,只是擺脫最終平均前的底片拍攝)

+0

你能做到這一點更簡單地使用[numpy.loadtxt(http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html),基本上做很多東西,你的代碼並且操作數值數組是'numpy'的用處。 –

回答

2

我不知道這是你的意思,但你可以像這樣更改你的意思功能:

def mean(B): 
     positives = [b for b in B if b >= 0] 
     return sum(positives)/len(positives) 

這會給你的B的非負面成員的平均值是你想要的那種?

一般來說,理解是獲取列表的非負成員的一種方式。另一種更有意義的方法是

filter (lambda i: i >=0, some_list) 

雖然這似乎正在經歷一些折舊。

+0

是的!但是我得到這個錯誤「迴歸總和(陽性)/ LEN(陽性) ZeroDivisionError:浮動師 – KJo

+3

你需要捕捉的情況下積極爲空。 '如果肯定:返回總和(正數)/ len(正數)否則:返回0' – llb