votes up 1

Axis must be specified when shapes of a and weights differ.

Package:
numpy
github stars 18118
Exception Class:
TypeError

Raise code

lt_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')
        else:
            result_dtype = np.result_type(a.dtype, wgt.dtype)

        # Sanity checks
        if a.shape != wgt.shape:
            if axis is None:
                raise TypeError(
                    "Axis must be specified when shapes of a and weights "
                    "differ.")
            if wgt.ndim != 1:
                raise TypeError(
                    "1D weights expected when shapes of a and weights differ.")
            if wgt.shape[0] != a.shape[axis]:
                raise ValueError(
                
😲  Walkingbet is Android app that pays you real bitcoins for a walking. Withdrawable real money bonus is available now, hurry up! 🚶

Ways to fix

votes up 1 votes down

Explanation: To compute the weighted average of an array the shape of the array and the specified weight must match. Or the axis along which the array a should be averaged must be specified and its length must match with the given 1-D weight. E.g. if the shape of the given array is (3,4) the weight array must be the shape as the array. Or

if we want to average along the rows the axis must be 0 and and the wight should be 1-D array with length of 3.

Code to reproduce the error:

import numpy as np
data = np.arange(12).reshape((3,4))
weights = weights=[1./4, 3./4,2.]
average = np.average(data,weights=weights)
print(average)

Fixed code:

from the above code we should add the argument axis = 0.

import numpy as np
data = np.arange(12).reshape((3,4))
weights = weights=[1./4, 3./4,2.]
average = np.average(data,axis=0,weights=weights)
print(average)
# if we want to average along axis=1 the length of the weight array should be 4

For more info refer to the documentation here

May 19, 2021 kellemnegasi answer
kellemnegasi 31.6k

Add a possible fix

Please authorize to post fix