Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use sum()/average() for namedtuple in python?

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
points = [Point(x=1.0, y=1.0), Point(x=2.0, y=2.0)] 

I'd like to compute the average point out of points list, i.e. receive Point(1.5, 1.5) as a result:

point = average(points) # x = 1.5, y = 1.5

E.g. I know there's np.average(points, axis=0) if points.shape is (N, 2), but I'd rather keep a named tuple instead.

like image 471
Alex Avatar asked Jul 28 '26 00:07

Alex


1 Answers

Calculate the average coordinate-wise:

import numpy as np
Point(np.average([p.x for p in points]),
      np.average([p.y for p in points]))
#Point(x=1.5, y=1.5)

Or, better, implicitly convert the list of points to a numpy array, get the average, and convert the result back to a Point

Point(*np.average(points, axis=0))
#Point(x=1.5, y=1.5)
like image 56
DYZ Avatar answered Jul 30 '26 13:07

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!