1

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

Package:

numpy

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(
```

## Links to the raise (2)

https://github.com/numpy/numpy/blob/5f3c3181b5d8db0e430e5f605cc45c4392f04934/numpy/lib/function_base.py#L393 https://github.com/numpy/numpy/blob/5f3c3181b5d8db0e430e5f605cc45c4392f04934/numpy/ma/extras.py#L606## See also in the other packages (2)

(❌️ No answer)

jax/axis-must-be-specified-when-shapes-o
(❌️ No answer)

dask/axis-must-be-specified-when-shapes-
## Ways to fix

1

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

### Add a possible fix

Please authorize to post fix