Nick Charlton Nick Charlton - 1 month ago 11
Python Question

Mean of lines in data file

I need to make a function that computes the mean of each line of numbers in a data file (.csv) and then returns the means as a list.

I have managed to get values for the numbers added together but I can't figure out how to divide by the length of each line of data and then feed the result into a list to be returned.

def line_averages(filename):
""" compute the average value for every line, and return the average
values in a list in the file "filename" """
infile = open(filename, "r")
all_input = infile.read()
infile.close()
lines = all_input.split('\n') # remove lines
for one_line in lines:
values = one_line.split(',') # remove commas
line_sum = 0
print(values)
for j in values:
line_sum = line_sum + float(j)


Update:

this is the new code I have as per one of the suggestions below:

def line_averages(filename):
""" compute the average value for every line, and return the average
values in a list in the file "filename" """
f = open(filename, "r")
x = f.read()
f.close()
no_lines = x.split('\n') # remove lines
means = []
for i in no_lines:
no_commas = i.split(',') # remove commas
average = sum(no_commas) / len(no_commas)
means.append(average)
return means


I get this error:

In [22]: line_averages("data.csv")
Traceback (most recent call last):

File "<ipython-input-29-e2e3fddb5de5>", line 1, in <module>
line_averages("data.csv")

File "E:/Google Drive/python_files/training4.py", line 19, in line_averages
average = sum(no_commas) / len(no_commas)

TypeError: unsupported operand type(s) for +: 'int' and 'str'


not sure what's gone wrong?!

Answer
return_list = []
...
    average = sum(values) / len(values)
    return_list.append(average)

Also, please use descriptive variable names. Single-letter variables are okay for throw-away indices, but not for anything with a lasting meaning.