user14457394
user14457394

Reputation:

How to find centroid in lists with N elements?

I'm trying to find the centroid for n points in lists. I've written code below which calculates the centroid in lists where n = 3, but not where n could be any number.

How could I edit the below code so that it would work if e.g. list1 values contained 4 or 5 elements instead of 3 like they currently do, without having to define coords4 and coords5?

list1 = [[1,4,0], [0,4,1], [1,8,0], [1,8,0], 
            [2,13,1], [12,11,0]]

def centroid(*args):
    coords1 = [p[0] for p in list1]
    coords2 = [p[1] for p in list1]
    coords3 = [p[2] for p in list1]
    _len = len(list1)
    centroid1 = sum(coords1)/_len
    centroid2 = sum(coords2)/_len
    centroid3 = sum(coords3)/_len
    return [centroid1, centroid2, centroid3]

centroid(list1)

Out:

[2.833, 8.0, 0.333]

Upvotes: 0

Views: 1374

Answers (2)

LevB
LevB

Reputation: 953

If you want efficient code, you are better off using numpy. This will work for any dimension. No loops.

import numpy as np
arr1 = np.array([[1,4,0], [0,4,1], [1,8,0], [1,8,0], 
        [2,13,1], [12,11,0]])
        
print(np.mean(arr1,axis=0))

Output :

[2.83333333 8.         0.33333333]


        

Upvotes: 2

Abhinav Mathur
Abhinav Mathur

Reputation: 8101

Simple, readable for loop without using extra functions

n = len(list1[0])
centroid = [0]*(n)
for i in range(n):
    total = sum([item[i] for item in list1])
    centroid[i] = total/len(list1)
print(centroid)

Upvotes: 3

Related Questions