mateuszm
mateuszm

Reputation: 35

Average of one index of pairs of numbers

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

Answers (3)

Sanjay Subramaniam
Sanjay Subramaniam

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

DarrylG
DarrylG

Reputation: 17166

Also:

def average(data):
    return sum(x[0] for x in data)/len(data)

Upvotes: 1

kederrac
kederrac

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

Related Questions