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(
                
😲 Agile task management is now easier than calling a taxi. #Tracklify
🙏 Scream for help to Ukraine
Today, 3rd July 2022, Russia continues bombing and firing Ukraine. Don't trust Russia, they are bombing us and brazenly lying in same time they are not doing this 😠, civilians and children are dying too! We are screaming and asking exactly you to help us, we want to survive, our families, children, older ones.
Please spread the information, and ask your governemnt to stop Russia by any means. We promise to work extrahard after survival to make the world safer place for all.

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 30.0k

Add a possible fix

Please authorize to post fix