Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Means in Numpy with tuples

I have a list of tuples, and for some of the operations I need to do, I need to find the mean, but i’m having a problem that I don’t quite understand.

# This works
weeks = [(1, 7),
         (8, 14),
         (15, 21),
         (22, 28),
         (29, 35),
         (36, 44)
         ]

# This doesn't work
np.mean(weeks[0][0], weeks[0][1])

I’m sure this is simple, but I dont understand the error: AxisError: axis 7 is out of bounds for array of dimension 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could convert weeks to a numpy array and use the mean method:

np.array(weeks).mean()

Output:

21.666666666666668

You can also use the axis argument to calculate the mean of the ‘rows’ and ‘columns’:

print(np.array(weeks).mean(axis=0))
print(np.array(weeks).mean(axis=1))

Output:

array([18.5       , 24.83333333])
array([ 4., 11., 18., 25., 32., 40.])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading