average across list of 2d arrays [python]

Viewed 113

I have a list = [D1, D2, D3, ...] where each DX is a 2d Array of simmilar dimensions (let's say 4x5). I now want to average the DX. So my result 2d Array should for example be:

result[0,0] = (D1[0,0] + D2[0,0] + ...) / len(list)
result[0,1] = (D1[0,1] + D2[0,1] + ...) / len(list)
etc.

Is there a neat function for this? I somehow can't find the correct terms for googeling this..

3 Answers

Any kind of linear algebra or other tensor operations in python gets a lot more convenient and readable with the numpy library.

You can install it with pip: pip install numpy

What you're trying to accomplish (element-wise average), would be done as such:

import numpy as np

results = np.stack([D1, D2, D3, ...]).mean(axis=0)

You can convert the list of numpy arrays to a numpy array, the resulting array will be 3D array, and you can calculate the mean on any axis (0,1,2), you want. For your use case, you need to pass axis=2 i.e. the outermost axis

arr = np.array([np.random.randint(0,5, (4,5)) for i in range(5)])
#arr
[[[1 4 4 0 0]
  [4 0 0 1 2]
  [0 4 3 0 1]
  [2 2 2 3 0]]
 [[1 3 3 3 0]
  [1 2 4 2 2]
  [2 3 1 3 0]
  [3 3 4 1 2]]
 [[2 4 1 0 4]
  [3 3 3 2 2]
  [4 0 1 4 0]
  [0 1 1 2 3]]
 [[0 3 3 0 1]
  [3 3 1 4 2]
  [2 3 2 4 2]
  [3 2 1 1 0]]
 [[0 0 2 0 1]
  [4 0 3 2 3]
  [1 4 1 1 3]
  [1 2 0 4 2]]]
#arr.mean(axis=2)  # For your expected output
[[0.8 2.8 2.6 0.6 1.2]
 [3.  1.6 2.2 2.2 2.2]
 [1.8 2.8 1.6 2.4 1.2]
 [1.8 2.  1.6 2.2 1.4]]
# arr.mean(axis=1)
[[1.75 2.5  2.25 1.   0.75]
 [1.75 2.75 3.   2.25 1.  ]
 [2.25 2.   1.5  2.   2.25]
 [2.   2.75 1.75 2.25 1.25]
 [1.5  1.5  1.5  1.75 2.25]]
# arr.mean(axis=0)
[[1.8 1.4 1.6 1.8]
 [2.  2.2 1.8 2.6]
 [2.2 2.6 1.8 1.4]
 [1.4 2.6 2.6 1.4]
 [0.6 2.4 2.  1.8]]

You should try to use numpy.mean() . Probably you can create the same list with numpy, and then calculate the mean for axis=None, and you can get the average of the whole list of matrices.

Related