如何使用python查找文件中多列的平均值

时间:2010-09-11 22:55:14

标签: 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 个答案:

答案 0 :(得分: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的第一个参数可能是文件的名称,而不是像object这样的文件。

答案 1 :(得分: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

答案 2 :(得分:1)

您可以使用内置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

答案 3 :(得分:0)

答案少于对问题的另一种理解:

你可以认为每一行都是一个向量。通过这种方式,逐列完成的平均值就是这些向量中每一个的平均值。你需要的只是

  1. 将线条读入矢量对象的方法,

  2. 向量添加操作

  3. 向量的标量乘法(或除法)。

  4. Python(我认为)已经安装了大部分内容,但这应该会导致一些易于理解的代码。