Home > other >  Means in Numpy with tuples
Means in Numpy with tuples

Time:07-11

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

CodePudding user response:

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

CodePudding user response:

Not a numpy answer, but for a list of tuples you can use mean from the python statistics library, which takes a list or tuple as input and returns a mean.

from statistics import mean
weeks = [(1, 7),
         (8, 14),
         (15, 21),
         (22, 28),
         (29, 35),
         (36, 44)
         ]

print(mean(weeks[0]))

CodePudding user response:

do you want find the mean of total elements or only of one axis? for the first time try this

 weeks = [(1, 7),
     (8, 14),
     (15, 21),
     (22, 28),
     (29, 35),
     (36, 44)
     ]
  n.mean(weeks)

CodePudding user response:

Do you want like this?

for tup in weeks:
        print(np.mean(tup))
  • Related