Reputation: 35
I have a table like [[2,3], [7,6], [12,567],[18,4]]. I need average of elements 2, 7, 12, 18.
def average(data):
temp = []
for x in data:
temp.append(x[0])
return np.average(temp)
Is there a better way?
Upvotes: 1
Views: 56
Reputation: 98
My answer is an ELI5 version of @kederrac's. If you got that, skip this.
Your solution is correct, we'll just polish it minimally, in one place only.
temp = []
for x in data:
temp.append(x[0])
Shrink that to one line with listcomps. I'm renaming x
to row
, I like variable names that click right away.
temp = [row[0] for row in data]
That's it; the rest of your solution is neat.
return np.average(temp)
Good luck :)
Upvotes: 1
Reputation: 17166
Also:
def average(data):
return sum(x[0] for x in data)/len(data)
Upvotes: 1
Reputation: 17322
you could use:
from statistics import mean
mean(e[0] for e in data)
or:
np.average([e[0] for e in data])
output:
9.75
or:
np.average(np.array(data)[:,0])
also @WillemVanOnsem suggestion is great:
np.array(data)[:,0].mean()
def average(data):
np.average([e[0] for e in data])
Upvotes: 2