2013-04-26 102 views
0

我有一些在csv文件中讀取的代碼。代碼然後根據用戶輸入添加值。我遇到的問題是刪除包含無效值的條目。特定的無效值將爲M.我在我的csv文件中使用M缺失。所以基本上我想要做的是讓用戶輸入開始和結束的月份,然後讓代碼疊加降水值。但是,如果字符串應該包含M,我不想包含該行數據。例如...部分樣本包括在下面。基於python中的值刪除行

Station,  Stat,  lat,  lon,  JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG 
Bainville 6 NE, 24-0408-06, 48.14065, -104.267, 0.10, 0.01, 0.12, 1.23, 0.02, 0.34, M, 0.00 
Brockton 20S, 24-1164-06, 47.5075, -104.324, M, 0.08, 0.13, 1.54, 2.43, 1.23, 1.12, 0.9 
Cohagen,  24-1875-06, 47.564, -106.7, 0.3, 0.37, M, 0.76, 1.55, 1.69, 0.35, 0.41 
Sidney,   24-7560-06, 47.36, -104.47, 0.1, 0.21, 0.05, 1.21, M, 1.25, 2.75, 0.89 

現在,如果用戶選擇月日至月那麼我想什麼有發生的是,Brockten行(月)和Cohagen行(MAR)被省略的值是M.但是,如果用戶選擇幾個月通過可能然後該行被省略將是Sidney。

我希望這是有道理的。我知道這篇文章已經很長了,但我也會包含我的代碼。

################################################## 
import csv 
import array 
import decimal 
decimal.getcontext().prec = 4 
from time import gmtime, strftime 
print strftime("%Y-%m-%d %H:%M:%S", gmtime()) 

# Create an unordered MON to column number dictionary and get user data 
mdict = {'MAR': 11, 'FEB': 10, 'AUG': 16, 'SEP': 17, 'APR': 12, 'JUN': 14, 
     'JUL': 15, 'JAN': 9, 'MAY': 13, 'NOV': 19, 'DEC': 20, 'OCT': 18} 

month_start = raw_input('Input the 3 letter ID of beginning month: ') 
month_end = raw_input('Input the 3 letter ID of ending month: ') 
month_start = month_start.upper() 
month_end = month_end.upper() 
mon_layer_name = month_start + ' through ' +month_end 
user_month = '[' + mon_layer_name + ']' 
start_num = mdict[month_start] 
end_num = mdict[month_end]+1 
new_list = [['Station', 'Lat', 'Long', 'mysum']] 

with open('R:\\COOP\\temp\\COOP_rainfall2.csv', 'rb') as csvfile: 
    filereader = csv.reader(csvfile) 
    filereader.next() # this is to skip header 
    for row in filereader: 
     #print row 
     sta = row[0] 
     lat = row[2] 
     lon = row[3] 
     tot = decimal.Decimal(0) 
     for x in row[start_num:end_num]: 
      print 'now in line 34 in code' 
      if x == '': x = 0 
      elif x == 'M': # I think this is where I need to do something just not sure how ot accomplish it. 
       x = 0 
       print row 
      tot = tot + decimal.Decimal(x) 
     if tot == 0: continue 
     else: new_list.append([sta, lat, lon, str(tot)]) 

with open('R:\\COOP\\temp\\output.csv', 'wb') as csvout:   
    print 'Now in file writer code block' 
    filewriter = csv.writer(csvout) 
    for line in new_list: 
      filewriter.writerow(line) 

Rex = 'R:\\COOP\\temp\\output.csv' 
Precip=[] #creating an array named Precip 
inp = open (Rex,"r") 
for line in inp.readlines(): 
line.split(',') 
Precip.append(line) 
file.close(inp) 
print 'End of code' 

任何幫助,非常感謝。

回答

0

在代碼工作之前,有一些問題需要解決。我並不確信你要完成的是什麼,但這裏有一些建議:

對於你提供的樣本數據,mdict值不正確 - JAN位於你的標題行的位置3。

理想情況下,您可以通過解析CSV的第一行而不是將其扔掉來程序化查找。你可以試試這個...

header_row = filereader.next() # if the months might NOT be uppercase, fix that here... 
start_num = header_row.index(month_start.upper()) 
end_num = header_row.index(month_start.upper()) 

後你有固定的,你可以在列表中檢查是否有「M」,並使用SUM()與理解做加法。因爲我不知道你想怎麼處理「好」行,我給的,你可以找一個答案感...

# first, see if 'M' is any of the values in the range you are looking for 
if 'M' in row[start_num:end_num]: 
    # skip this row 
    pass 
# if 'M' is not one of the values, do the math with a built in function instead of 
# writing the loop yourself (this uses a comprehension too... that is a replacement for your loop. 
else: 
    total = sum((decimal.Decimal(x) for x in row[start_num:end_num])) 

澄清你需要一點點,我也許能夠幫助你更多...

湯姆

0

可以確認,如果某些單元格中包含一個浮動的(有效),而不是一個字符的代碼象下面這樣:

def is_number(s): 
try: 
    float(s) # for int, long and float 
    return true 
except ValueError: 
    return False 

一旦一個「問題」行被確定你可以通過拼接刪除該行,其代碼類似如下:

>>> print(a) 
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 'M', 3], [4, 4, 4], [5, 5, 5]] 
>>> problemRow =3 # would really use is_number here to identify row 3 
>>> a[0:problemRow] 
[[0, 0, 0], [1, 1, 1], [2, 2, 2]] 
>>> a[problemRow+1:] # nothing after the colon - extend to end 
[[4, 4, 4], [5, 5, 5]] 
>>> b = a[0:problemRow] 
>>> b.append(a[problemRow+1:]) 
>>> print(b) 
[[0, 0, 0], [1, 1, 1], [2, 2, 2], [[4, 4, 4], [5, 5, 5]]]