Implement the weighted average between two 2D arrays

Viewed 436

Assume I want to take the weighted average between two 2D arrays, say x and y, where I want to give y higher importance than x. I understand that numpy.average does that but I would like to see an example that works for this case of mine.

Thank you in advance.

1 Answers

If x and y have the same shape you can evaluate the weighted average between each pair of elements (one per array) and then the mean of them.

import numpy as np

x = np.array([100,200,300])
y = np.array([1,2,3])

print(
  np.mean(
    np.average([x,y], weights=[1,100], axis=0)
  )
)

Or for generic arrays you could use the definition of weighted sum:

import numpy as np

x = np.array([100,200,300])
y = np.array([1,2,3])

x_w = 1
y_w = 100

print(
  (np.sum(x)*x_w + np.sum(y)*y_w) / (x.size*x_w + y.size*y_w)
)
Related