从文本文件中获取矩阵的行列平均值

时间:2018-06-17 13:27:46

标签: python file text average

我的问题是如何获得每个矩阵的平均值并将其写入新的文本文件中。

如果文字内容是

1 -20 -100 50 60
3 4 -100 -3 
-10 5 45 10 -15\n

我想在不使用numpy的情况下得到这样的结果:

1 -20 -100 50 60  avg : -2
3 4 -100 -3 0     avg : -20
-10 5 45 10 -15   avg : 7
-2 -4 -52 19 15

这是我的代码:

with open('number.txt','r') as file1:
    file2 = open('text2.txt','w')
    line = file1.readlines()
    for i in range(len(line)):
        a = str(line[i])
        a.split()
        b = a.split()
        for j in range(len(b)):
            sum(int(b[0][i]))/len(b)
        for z in range(len(b)):
            sum(int(b[i][0]))/len(b) 

4 个答案:

答案 0 :(得分:1)

new:ziperdyzip

您似乎不想出于某种原因使用NumPy。好吧:这不是使用numpy:

rowMean = [sum(row)//len(row) for row in data]
colmean = [sum(col)//len(col) for col in list(map(list, zip(*data)))]

完整示例:

with open('number.txt', 'r') as file1:
    data = file1.readlines()
data = [line.split() for line in data]
data = [list(map(int, row)) for row in data]

outData = [list(map(str, row)) + ['avg :', str(sum(row)//len(row)), '\n'] for row in data]
outData.append([str(sum(col)//len(col)) for col in list(map(list, zip(*data)))])

with open('text2.txt', 'w') as file2:
    file2.writelines([' '.join(row) for row in outData])

或者使用右对齐形式的紧凑形式:

with open('output.txt', 'w') as outfile, open('number.txt', 'r') as infile:
    data = [list(map(int, line.split())) for line in infile.readlines()]
    outfile.writelines([' '.join([str(el).rjust(4) for el in row] + ['avg :', str(sum(row)//len(row)).rjust(4), '\n']) for row in data])
    outfile.write(' '.join([str(sum(col)//len(col)).rjust(4) for col in list(map(list, zip(*data)))]))

输出:

   1  -20 -100   50   60 avg :   -2 
   3    4 -100   -3    0 avg :  -20 
 -10    5   45   10  -15 avg :    7 
  -2   -4  -52   19   15

old:Numpy

您可以使用NumPy

data = [[1, -20, -100, 50, 60],
        [3, 4, -100, -3, 0],
        [-10, 5, 45, 10, -15]]

import numpy as np

colMean = np.floor(np.mean(data,0)).astype(int).tolist()
rowMean = np.floor(np.mean(data,1)).astype(int).tolist()

我使用了np.floor(),因为您的示例似乎要向下舍入。

答案 1 :(得分:0)

这是一个例子,使用numpy只是为了方便而且因为它允许进行更复杂的计算,但你可以用你的公式代替它。

import numpy as np

with open('number.txt','r') as file1:
    file2 = open('text2.txt','w')
    line = file1.readlines()
    for i in range(len(line)):
        #print(line )
        a = str(line[i]).replace('\n','')
        b = [int(n.replace('\\n','')) for n in a.split()]
        text = a+' avg: '+ str( np.mean(b) ) + ' \n '
        file2.write( text )
file2.close()

答案 2 :(得分:0)

换行字符已从集合中删除,因为它会产生错误。

1 -20 -100 50 60  
3 4 -100 -3  
-10 5 45 10 -15
with open('number.txt','r') as file1:
    file2 = open('text2.txt','w')
    line = file1.readlines()

    for s in line:
        # get the individual data and make them floating-point
        data = map(float, s.split()) 

        # doing stuffs with the data
        print(sum(data) / len(data))

在@SpghttCd评论后更新了我的答案。您现在应该可以访问列。

with open('number.txt','r') as file1:
    file2 = open('text2.txt','w')

    # recreating the matrix get the individual data and make them floating-points
    m = list([map(float, s.split()) for s in file1.readlines()])

    # calculations in lines
    print(sum(m[0]) / len(m[0]))
    print(sum(m[1]) / len(m[1]))
    print(sum(m[2]) / len(m[2]))

    # calculations in columns
    c = [l[0] for l in m]
    print(sum(c) / len(c))

    # or in a way more like what you tried
    tmp = 0
    for j in range(len(m)): # accessing the first columns of each line of the matrix
        tmp += int(m[j][0]) / len(m[j])
    print(tmp)

答案 3 :(得分:0)

container.appendChild( renderer.domElement );