Harry Reid
Harry Reid

Reputation: 99

Get average column value from list of arrays Python

I'm trying to get the average value of values in column 1 and column 2 of a list of arrays. I am using a dict called clusters with an index of clusterNo where I iterate through clusterNo.

print(kMeans.clusters[clusterNo])

When I print the dictionary it gives me this result:

[array([ 5.1,  3.5]), array([ 4.9,  3. ]), array([ 4.7,  3.2]), array([ 4.6,  3.1]), array([ 5. ,  3.6])

etc etc..

I cannot figure out how to slice into columns and then get the average. Bare in mind they are float values so I cannot simply avg() them.

Upvotes: 1

Views: 2220

Answers (1)

timgeb
timgeb

Reputation: 78770

Setup

>>> import numpy as np                                                                                                       
>>> lst = [np.array([ 5.1,  3.5]), np.array([ 4.9,  3. ]), np.array([ 4.7,  3.2]), np.array([ 4.6,  3.1]), np.array([ 5. ,  3.6])]

Solution

>>> np.mean(lst, axis=0)                                                                                                          
array([4.86, 3.28])

However, having lst as an array might be advantageous if you need to do more calculations or array operations on that data.

>>> arr = np.array(lst)                                                                                                              
>>> arr                                                                                                                           
array([[5.1, 3.5],
       [4.9, 3. ],
       [4.7, 3.2],
       [4.6, 3.1],
       [5. , 3.6]])
>>> arr.mean(axis=0)                                                                                                              
array([4.86, 3.28])

Upvotes: 2

Related Questions