-5

I have a list of size (201, 201) and i would like to calculate the mean of every 9 elements inside my list. For instance [[1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45]]. I am expecting an output like this:

[5, 14, 23, 28, 45]

I followed this question for example but unfortunately the question deals with arrays: Averaging over every n elements of a numpy array

I also followed this question: Python - Average every "n" elements in a list, but it calculates the mean from n+1 to n elements.

Im looking for a reproducible example for the list above for instance, that is a start for me i guess

  • 6
    What did you tried so far. It is not cool to let others write the entire code for you. Just add what you have tried so far and you show your willingness to at least try to find a solution. – MisterNox Jul 15 '20 at 21:30
  • 2
    [`numpy.mean`](https://numpy.org/doc/stable/reference/generated/numpy.mean.html) has an `axis` argument for this – user8408080 Jul 15 '20 at 21:30
  • 1
    alternative: `[sum(nums) / len(nums) for nums in nested_nums]`... result is `[5.0, 14.0, 23.0, 31.5, 40.5]`, btw. – matheburg Jul 15 '20 at 21:44

3 Answers3

1

Here is what you need:

my_list = [[1,2, 3, 4, 5, 6, 7, 8, 9], 
       [10, 11, 12, 13, 14, 15, 16, 17, 18], 
       [19, 20, 21, 22, 23, 24, 25, 26, 27], 
       [28, 29, 30, 31, 32, 33, 34, 35], 
       [36, 37, 38, 39, 40, 41, 42, 43, 44, 45]]

avg_list = []

for item in my_list:
    avg = int(sum(item)/len(item))
    avg_list.append(avg)
1

The statistics library has a mean function for this as well.

from statistics import mean

averages = list(map(mean, my_list))

Results:

[5, 14, 23, 31.5, 40.5]
Jab
  • 26,853
  • 21
  • 75
  • 114
0

One way to do this is by map with a lambda function:

A = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45]]
means = list(map(lambda x: np.mean(x), A))

Cheers.

Michael
  • 2,167
  • 5
  • 23
  • 38