Search code examples
pythonnumpyweighted-average

How to simply pass weights while np.average()


I am confused about passing weights into np.average() function. Example below:

import numpy as np

weights = [0.35, 0.05, 0.6]
abc = list()

a = [[ 0.5,  1],
   [ 5,  7],
   [ 3,  8]]

b = [[ 10,  1],
   [ 0.5,  1],
   [ 0.7,  0.2]]

c = [[ 10,  12],
   [ 0.5,  13],
   [ 5,  0.7]]

abc.append(a)
abc.append(b)
abc.append(c)

print(np.average(np.array(abc), weights=[weights], axis=0))

OUT:
TypeError: 1D weights expected when shapes of a and weights differ.

I know that shapes differ, but how to add simply list of weights without doing

np.average(np.array(abc), weights=[weights[0], weights[1], weights[2]], ..., axis=0)

because i am performing a loop, where weights differ with size up to 30.

Output: Weighted array like this:

OUT:
[[6.675,  7.6],
[ 2.075,  10.3],
[ 4.085,  3.23]]

*average(a * weights[0] + b * weights[1] + c * weights[2])*

Welcoming any other solution.


Solution

  • Not sure how the first element can be 4.675?

    weights = [0.35, 0.05, 0.6]
    
    
    a = [[ 0.5,  1],
       [ 5,  7],
       [ 3,  8]]
    
    b = [[ 10,  1],
       [ 0.5,  1],
       [ 0.7,  0.2]]
    
    c = [[ 10,  12],
       [ 0.5,  13],
       [ 5,  0.7]]
    
    abc=[a, b, c]
    
    print(np.average(np.array(abc), weights=weights,axis=0))