使用Python计算多个文件记录的平均值

1 投票
3 回答
2953 浏览
提问于 2025-04-16 06:56

大家好,
我刚开始学习Python,想找出在Python中做以下事情的最佳方法:假设我有三个文本文件,分别叫做A、B和C,每个文件都有m行n列的数字。接下来,文件中的内容可以用A[i][j]B[k][l]这样的方式来索引。我需要计算A[0][0]B[0][0]C[0][0]的平均值,并把结果写入文件D的D[0][0]。其他的记录也要这样做。比如,假设:

A:  
1 2 3   
4 5 6  
B:  
0 1 3  
2 4 5  
C:  
2 5 6  
1 1 1

因此,文件D应该是

D:  
1     2.67   4    
2.33  3.33   4  

我的实际文件当然比现在的要大,可能有几兆字节。我不太确定最好的解决方案是怎样的,是把所有文件的内容都读到一个嵌套结构中,然后用文件名来索引,还是对每个文件逐行读取并计算平均值。在看了手册后,发现fileinput模块在这种情况下不太有用,因为它不能“并行”读取行,而是“串行”读取。我非常感谢任何指导或建议。

3 个回答

0

这里给大家一个参考,告诉你如果不使用numpy,怎么做类似的事情(虽然不那么优雅,但更灵活):

files = zip(open("A.dat"), open("B.dat"), open("C.dat"))
outfile = open("D.dat","w")
for rowgrp in files:     # e.g.("1 2 3\n", "0 1 3\n", "2 5 6\n")
    intsbyfile = [[int(a) for a in row.strip().split()] for row in rowgrp]
                         # [[1,2,3], [0,1,3], [2,5,6]]
    intgrps = zip(*intsbyfile) # [(1,0,2), (2,1,5), (3,3,6)]
    # use float() to ensure we get true division in Python 2.
    averages = [float(sum(intgrp))/len(intgrp) for intgrp in intgrps]
    outfile.write(" ".join(str(a) for a in averages) + "\n")

在Python 3中,zip会根据需要读取文件。而在Python 2中,如果文件太大,无法一次性加载到内存中,可以使用itertools.izip来处理。

0

如果你在处理文本文件,可以试试这个:

def readdat(data,sep=','):
    step1 = data.split('\n')
    step2 = []
    for index in step1:
        step2.append(float(index.split(sep)))
    return step2

def formatdat(data,sep=','):
    step1 = []
    for index in data:
        step1.append(sep.join(str(data)))
    return '\n'.join(step1)

然后使用这些函数把文本格式化成列表。

1

你可以看看numpy这个库。它可以把三个文件读进三个数组(用的是fromfile这个功能),然后计算它们的平均值,并把结果导出到一个文本文件里(用的是tofile这个功能)。

import numpy as np


a = np.fromfile('A.csv', dtype=np.int)   
b = np.fromfile('B.csv', dtype=np.int)   
c = np.fromfile('C.csv', dtype=np.int)   

d = (a + b + c) / 3.0

d.tofile('D.csv')

文件大小“几MB”应该没什么问题。

撰写回答