如何使用Python计算文件中多个列的平均值
你好,我有一个文件,里面的列太多了,无法在Excel中打开。每一列有10行数字,数字范围是0到2,并且每列的第一行是列的标题。我想要的输出是列的名称和这10行的平均值。这个文件太大,Excel 2000打不开,所以我得试试用Python。你有什么简单的方法可以推荐吗?
这里是前3列的样本:
试验1 试验2 试验3
1 0 1
0 0 0
0 2 0
2 2 2
1 1 1
1 0 1
0 0 0
0 2 0
2 2 2
1 1 1
我希望Python能输出一个测试文件
试验1 试验2 试验3
1 2 1(无论平均值是多少)
4 个回答
1
你可以使用Python自带的csv
模块:
import csv
csvReader = csv.reader(open('input.txt'), delimiter=' ')
headers = csvReader.next()
values = [map(int, row) for row in csvReader]
def average(l):
return float(sum(l)) / len(l)
averages = [int(round(average(trial))) for trial in zip(*values)]
print ' '.join(headers)
print ' '.join(str(x) for x in averages)
结果:
Trial1 Trial2 Trial3 1 1 1
2
你可以使用 Numpy 这个库:
import numpy as np
from StringIO import StringIO
s = StringIO('''\
Trial1 Trial2 Trial3
1 0 1
0 0 0
0 2 0
2 2 2
1 1 1
1 0 1
0 0 0
0 2 0
2 2 2
1 1 1
''')
data = np.loadtxt(s, skiprows=1) # skip header row
print data.mean(axis=0) # column means
# OUTPUT: array([ 0.8, 1. , 0.8])
需要注意的是,loadtxt
的第一个参数可以是你的文件名,而不一定是一个像文件那样的对象。
2
这是一个不使用任何模块的内存友好的解决方案:
with open("filename", "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
for index, summedRowValue in enumerate(sums):
print columns[index], 1.0 * summedRowValue / numRows