2010-09-24 75 views
1

嗨,這是我的問題。我有一個程序,可以在列中平均數據的平均值。 例python中if if循環的幫助

Bob 
1 
2 
3 

輸出

Bob 
2 

有些數據已經「娜的 所以對於喬

Joe 
NA 
NA 
NA 

我想這個輸出是NA

所以我寫了一個if else循環

問題是它不執行循環的第二部分,只打印出一個NA。有什麼建議麼?

這裏是我的程序:

with open('C://achip.txt', "rtU") as f: 
    columns = f.readline().strip().split(" ") 
    numRows = 0 
    sums = [0] * len(columns) 

    numRowsPerColumn = [0] * len(columns) # this figures out the number of columns 

    for line in f: 
     # Skip empty lines since I was getting that error before 
     if not line.strip(): 
      continue 

     values = line.split(" ") 
     for i in xrange(len(values)): 
      try: # this is the whole strings to math numbers things 
       sums[i] += float(values[i]) 
       numRowsPerColumn[i] += 1 
      except ValueError: 
       continue 

    with open('c://chipdone.txt', 'w') as ouf: 
     for i in xrange(len(columns)): 
      if numRowsPerColumn[i] ==0 : 
       print 'NA' 
      else: 
       print>>ouf, columns[i], sums[i]/numRowsPerColumn[i] # this is the average calculator 

的文件看起來像這樣:

Joe Bob Sam 
1 2 NA 
2 4 NA 
3 NA NA 
1 1 NA 

,並最終輸出的姓名和平均值

Joe Bob Sam 
1.5 1.5 NA 

好吧,我試過羅傑的建議現在我有這個錯誤:

回溯(最近通話最後一個):在F: 「/avy14.py C」,5號線,在 線路: 文件 ValueError異常:I/O操作上關閉的文件

下面是這個新代碼:

張開( 'C://achip.txt', 「RTU」)爲f:。 列= f.readline()條()分割(」「) 總和= [0] * LEN(列) 行= 0 用於線路f中: 線= line.strip() 如果不是行: 繼續

行+ = 1 爲COL,V在枚舉(line.split()): 如果總和[COL]不是無: 如果V == 「NA」: 總和[COL] =無 否則: 總和[COL] + = INT(v)

張開( 「C:/chipdone.txt」, 「W」)作爲出: 爲名稱,總和拉鍊(列,求和): 打印> >出,姓名, 如果總和無: 打印出來>>, 「NA」 其他: 打印出來>>,和/行

+0

使用「C:\\ file」或「c:/ file」,後者通常是首選;在許多情況下使用「//」將被錯誤地解釋(只是不在這個確切的一箇中)。 – 2010-09-24 14:59:27

+0

你能否粘貼一個源文件看起來像什麼的例子,以及完整輸出應該是什麼樣子的例子? – 2010-09-24 15:00:50

+0

...還有,你可以包括「循環的第二部分」的代碼?提供的代碼只包含兩個替代指令(if/else)... – mac 2010-09-24 15:03:36

回答

1
with open("c:/achip.txt", "rU") as f: 
    columns = f.readline().strip().split() 
    sums = [0.0] * len(columns) 
    row_counts = [0] * len(columns) 

    for line in f: 
    line = line.strip() 
    if not line: 
     continue 

    for col, v in enumerate(line.split()): 
     if v != "NA": 
     sums[col] += int(v) 
     row_counts[col] += 1 

with open("c:/chipdone.txt", "w") as out: 
    for name, sum, rows in zip(columns, sums, row_counts): 
    print >>out, name, 
    if rows == 0: 
     print >>out, "NA" 
    else: 
     print >>out, sum/rows 

當我得到列名時(它允許你有多個空格分隔符),我也會使用無參數版本的split。

關於你的編輯,包括輸入/​​輸出樣本,我一直在你的原始格式和我的輸出是:

 
Joe 1.75 
Bob 2.33333333333 
Sam NA 

此格式(的ColumnName,平均)列3行,但你可以改變輸出,如果你想,當然。 :)

+0

Roger查看我的編輯 – 2010-09-24 15:16:07

+0

@Robert:您編輯中包含的代碼與*之外的for循環誤判,與,*在for循環運行前關閉文件。更新我的代碼以顯示我的意思。 – 2010-09-24 15:18:53

+0

@Robert:我還看到我寫的代碼(在你包括這個例子之前)是錯誤的,因爲我誤解了你。固定。 – 2010-09-24 15:36:33

0

使用numpy的:

import numpy as np 

with open('achip.txt') as f: 
    names=f.readline().split() 
    arr=np.genfromtxt(f) 

print(arr) 
# [[ 1. 2. NaN] 
# [ 2. 4. NaN] 
# [ 3. NaN NaN] 
# [ 1. 1. NaN]] 

print(names) 
# ['Joe', 'Bob', 'Sam'] 

print(np.ma.mean(np.ma.masked_invalid(arr),axis=0)) 
# [1.75 2.33333333333 --] 
0

使用您的原代碼,我想補充一個循環和編輯打印語句

with open(r'C:\achip.txt', "rtU") as f: 
    columns = f.readline().strip().split(" ") 
    numRows = 0 
    sums = [0] * len(columns) 

    numRowsPerColumn = [0] * len(columns) # this figures out the number of columns 

    for line in f: 
     # Skip empty lines since I was getting that error before 
     if not line.strip(): 
      continue 

     values = line.split(" ") 

     ### This removes any '' elements caused by having two spaces like 
     ### in the last line of your example chip file above 
     for count, v in enumerate(values):  
      if v == '':  
       values.pop(count) 
     ### (End of Addition) 

     for i in xrange(len(values)): 
      try: # this is the whole strings to math numbers things 
       sums[i] += float(values[i]) 
       numRowsPerColumn[i] += 1 
      except ValueError: 
       continue 

    with open('c://chipdone.txt', 'w') as ouf: 
     for i in xrange(len(columns)): 
      if numRowsPerColumn[i] ==0 : 
       print>>ouf, columns[i], 'NA' #Just add the extra parts 
      else: 
       print>>ouf, columns[i], sums[i]/numRowsPerColumn[i] 

該解決方案還給出了羅傑的格式,不一樣的結果你想要的格式。