好的,我有下面的工作程序。它将打开一个列中的数据文件,该文件对于excel来说太大,并找到每个列的平均值:
示例数据为:
Joe Sam Bob
1 2 3
2 1 3
它又回来了
^{pr2}$这很好。问题是有些列的值是NA。我想跳过这个NA,计算剩余值的平均值 所以
Bobby
1
NA
2
应输出为
Bobby
1.5
这是我在这里的帮助下建立的现有程序。感谢任何帮助!在
with open('C://avy.txt', "rtU") as f:
columns = f.readline().strip().split(" ")
numRows = 0
sums = [0] * len(columns)
for line in f:
# Skip empty lines
if not line.strip():
continue
values = line.split(" ")
for i in xrange(len(values)):
sums[i] += int(values[i])
numRows += 1
with open('c://finished.txt', 'w') as ouf:
for index, summedRowValue in enumerate(sums):
print>>ouf, columns[index], 1.0 * summedRowValue / numRows
现在我有了这个:
打开('C://阿维.txt',“rtU”)作为f:
def get_averages(f):
headers = f.readline().split()
ncols = len(headers)
sumx0 = [0] * ncols
sumx1 = [0.0] * ncols
lino = 1
for line in f:
lino += 1
values = line.split()
for colindex, x in enumerate(values):
if colindex >= ncols:
print >> sys.stderr, "Extra data %r in row %d, column %d" %(x, lino, colindex+1)
continue
try:
value = float(x)
except ValueError:
continue
sumx0[colindex] += 1
sumx1[colindex] += value
print headers
print sumx1
print sumx0
averages = [
total / count if count else None
for total, count in zip(sumx1, sumx0)
]
print averages
上面写着:
回溯(最近一次呼叫): 文件“C:/avy10.py”,第11行,英寸 lino+=1 名称错误:未定义名称“lino”
以下是一个功能解决方案:
我在这里写了很多列表理解,这样你就可以打印出中间步骤,但这些都可能是原因的生成器。在
[为清晰起见编辑]
从文本文件中读取项时,它们将作为字符串而不是数字导入。这意味着,如果文本文件中有数字
3
,并将其读入Python,则需要在进行算术运算之前将字符串转换为数字。在现在,您有一个包含colums的文本文件。每列都有一个标题和一组项。每一项要么是一个数字,要么不是。如果它是一个数字,它将被函数
float
正确地转换,如果它不是一个有效的数字(也就是说,如果转换不存在),转换将引发一个称为ValueError
的异常。在因此,你会循环查看你的列表和项目,因为它已经在多个答案中得到了正确的解释。如果可以转换为浮点,请累积统计信息。如果没有,继续忽略这个条目。在
如果您需要更多关于什么是“duck typing”的信息(一种可以恢复为“最好请求原谅而不是请求许可”)的信息,请检查Wikipedia link。如果你开始接触Python,你会经常听到这个词。在
我的意思是你对下面的统计数据感兴趣。可以为表中的每一列使用该类的实例。在
干杯。在
下面的代码可以正确地处理不同的计数,还可以检测额外的数据。。。换句话说,它相当健壮。如果文件是空的(2)如果头行是空的,可以通过显式消息(1)来改进它。另一种可能是显式地测试
"NA"
,如果某个字段既不是"NA"
,也不是可浮动的,则发出错误消息。在编辑在此处添加:
^{pr2}$编辑
正常使用:
相关问题 更多 >
编程相关推荐