I have to calculate the average of each column in a specific nested list and then save the average into a new list. In my code so far, I have set the original list into a nested list and transposed it to read in the columns. I am just not sure how to code the average.
#First open the data text file
import re
f = open('C:\Python27\Fake1.txt', 'r')
#Convert to a nested list
nestedlist = []
q = f.read()
f.close()
numbers = re.split('\n', q) #Splits the \n and \t out of the list
newlist = []
for row in numbers:
newlist.append(row.split('\t'))
#Reading in columns
def mytranspose(nestedlist):
list_prime = []
for i in range(len(nestedlist[0])):
list_prime.append([])
for row in nestedlist:
for i in range(len(row)):
list_prime[i].append(row[i])
return(list_prime)
print (mytranspose(newlist))
#Average of Columns
def myaverage(nestedlist):
avg_list = []
a = 0
avg = 0
for i in newlist:
a = sum(newlist[i])
avg = a/len(row)
avg_list.append(avg[i])
return(list_prime)
print(myaverage(newlist))
Here is a simpler way to do the whole thing:
I would however recommend using numpy for this sort of thing as it becomes trivial (as well as much faster):