0

Here is two lists: list = [[1, 2], [3, 4]] and list = [1, 2, 2, 3, 4]

I would like to calculate the mean of the lists. This is my code thus far and outputs:

 def summary(x):
      mean1 = np.mean(x)

      Dict = {"mean":mean1}
 return Dict

summary([1, 2, 2, 3, 4])
My output is == {'mean': 2.4}

summary([[1, 2], [3, 4]])
My output is == error

I would just like to know what should i change to my code so that 2D arrays also work if i give it as input and not only just 1D arrays?

I have seen that i should insert (x, axis=1) but then it only works for 2Darray and not again for the 1D array.

I would like the 2D mean to give me output: 'mean': [1.5, 3.5]

Back Buddy
  • 35
  • 7
  • Does this answer your question? [Calculate mean across dimension in a 2D array](https://stackoverflow.com/questions/15819980/calculate-mean-across-dimension-in-a-2d-array) – Umair Mubeen Mar 30 '21 at 10:47
  • @UmairMubeen i have tried the np.mean(x, axis=1) but then it only works for the 2D array and when i try to run the 1D array it does not work – Back Buddy Mar 30 '21 at 10:51
  • `def summary(list):` should be `def summary(x):` – Nick Mar 30 '21 at 10:54
  • @Nick i have changed it. I would just like the function to give for my 2D array output: 'mean': [1.5, 3.5] – Back Buddy Mar 30 '21 at 10:58

2 Answers2

0

There is an error in the summary definition instead of list you want to have x as parameter.

With this it works fine for me:

import numpy as np
def summary(x):
    mean1 = np.mean(x)

    Dict = {"mean":mean1}
    return Dict

a = summary([1, 2, 2, 3, 4])
print(a)
b = summary([[1, 2], [3, 4]])
print(b)

Result is:

{'mean': 2.4}
{'mean': 2.5}

[Update]

If you want to have the mean along a specific axis you can do it like the following. You have to check the array shape, because you want it in direction 1, which is not prsent for a 1D array.

import numpy as np
def summary(x):
    arr = np.array(x)
    if len(arr.shape) == 2:
        mean1 = np.mean(arr, axis=1)
    else:
        mean1 = np.mean(arr)

    Dict = {"mean":mean1}
    return Dict

a = summary([1, 2, 2, 3, 4])
print(a)
b = summary([[1, 2], [3, 4]])
print(b)

which returns

{'mean': 2.4}
{'mean': array([1.5, 3.5])}
user_na
  • 2,154
  • 1
  • 16
  • 36
0

try this:

import numpy as np

def summary(x):
      mean1 = np.mean(x)
      Dict = {"mean":mean1}
      return Dict

print(summary([1, 2, 2, 3, 4]))

print(summary([[1, 2], [3, 4]]))
Nick
  • 138,499
  • 22
  • 57
  • 95