1

My question is how to get each matrix's average and write it in a new text file.

If contents of text is

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

I want to get result like this without using 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

Here is my code:

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) 
smci
  • 32,567
  • 20
  • 113
  • 146
신은화
  • 3
  • 3

4 Answers4

1

new: ziperdyzip

It seems you don't want to use NumPy for some reason. Well: this is not using numpy:

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

Complete example:

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])

Or in compact with right justification form:

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)))]))

output:

   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

You can use 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()

I used np.floor() as from your example it seems you want to round down.

Community
  • 1
  • 1
JHBonarius
  • 10,824
  • 3
  • 22
  • 41
0

Here is an example, using numpy just for ease and beacuse it allows to make more complex computations, but you can substitute it with your formula.

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()
GianAnge
  • 593
  • 3
  • 12
0

The newline character was removed from the set as it will generate an error.

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))

Updated my answer after @SpghttCd comment. You should now be able to access the columns.

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)
Remy J
  • 709
  • 1
  • 7
  • 18
0
with open(r"G:\python1.txt","r") as f1:
   with open(r"G:\output.txt","w") as f2:
    l=f1.readlines()
    for li in l:
        li=li.replace("\n","")
        temp=li.split(" ")
        sum=0
        for x in temp:
            avg=0
            sum=sum+int(x)
        avg=sum/len(temp)
        temp1=str(round(avg))
        l1=str(li)
        print("l1",l1)
        f2.write(l1+" "+ "avg:"+temp1)
        f2.write("\n")
anmol
  • 1