2010-09-24 79 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] 

该解决方案还给出了罗杰的格式,不一样的结果你想要的格式。