嗨,这是我的问题。我有一个计算列中数据平均值的程序。 示例
Bob
1
2
3
输出为
Bob
2
一些数据有“na” 所以对于乔来说
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
好吧,我尝试了罗杰的建议,现在我遇到了这个错误:
回溯(最近一次调用最后一次): 文件“C:/avy14.py”,第 5 行,位于 对于 f 中的行: ValueError:对已关闭文件进行 I/O 操作
这是新代码:
with open('C://achip.txt', "rtU") as f: 列 = f.readline().strip().split("") 总和 = [0] * len(列) 行=0 对于 f 中的行: 线 = 线.strip() 如果没有线: 继续
行 += 1 对于 col, v in enumerate(line.split()): 如果 sums[col] 不是 None: 如果 v == "NA": sums[列] = 无 别的: sums[col] += int(v)
以 open("c:/chipdone.txt", "w") 为例: 对于名称,zip 中的总和(列,总和): 打印>>输出,姓名, 如果总和为无: 打印>>输出,“NA” 别的: 打印>>输出,总和/行
最佳答案
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
此格式为 3 行 (ColumnName, Avg) 列,但当然,您可以根据需要更改输出。 :)
关于python - 帮助Python中的if else循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3788229/