Search code examples
pythonnumpytuplesmean

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


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.])