numpy.average#
- numpy.average(a,axis=None,weights=None,returned=False,*,keepdims=<novalue>)[source]#
Compute the weighted average along the specified axis.
- Parameters:
- aarray_like
Array containing data to be averaged. Ifa is not an array, aconversion is attempted.
- axisNone or int or tuple of ints, optional
Axis or axes along which to averagea. The default,axis=None, will average over all of the elements of the input array.If axis is negative it counts from the last to the first axis.If axis is a tuple of ints, averaging is performed on all of the axesspecified in the tuple instead of a single axis or all the axes asbefore.
- weightsarray_like, optional
An array of weights associated with the values ina. Each value ina contributes to the average according to its associated weight.The array of weights must be the same shape asa if no axis isspecified, otherwise the weights must have dimensions and shapeconsistent witha along the specified axis.Ifweights=None, then all data ina are assumed to have aweight equal to one.The calculation is:
avg=sum(a*weights)/sum(weights)
where the sum is over all included elements.The only constraint on the values ofweights is thatsum(weights)must not be 0.
- returnedbool, optional
Default isFalse. IfTrue, the tuple (
average,sum_of_weights)is returned, otherwise only the average is returned.Ifweights=None,sum_of_weights is equivalent to the number ofelements over which the average is taken.- keepdimsbool, optional
If this is set to True, the axes which are reduced are leftin the result as dimensions with size one. With this option,the result will broadcast correctly against the originala.Note:keepdims will not work with instances of
numpy.matrixor other classes whose methods do not supportkeepdims.New in version 1.23.0.
- Returns:
- retval, [sum_of_weights]array_type or double
Return the average along the specified axis. Whenreturned isTrue,return a tuple with the average as the first element and the sumof the weights as the second element.sum_of_weights is of thesame type asretval. The result dtype follows a general pattern.Ifweights is None, the result dtype will be that ofa , or
float64ifa is integral. Otherwise, ifweights is not None anda is non-integral, the result type will be the type of lowest precision capable ofrepresenting values of botha andweights. Ifa happens to beintegral, the previous rules still applies but the result dtype willat least befloat64.
- Raises:
- ZeroDivisionError
When all weights along axis are zero. See
numpy.ma.averagefor aversion robust to this type of error.- TypeError
Whenweights does not have the same shape asa, andaxis=None.
- ValueError
Whenweights does not have dimensions and shape consistent withaalong specifiedaxis.
See also
meanma.averageaverage for masked arrays – useful if your data contains “missing” values
numpy.result_typeReturns the type that results from applying the numpy type promotion rules to the arguments.
Examples
>>>importnumpyasnp>>>data=np.arange(1,5)>>>dataarray([1, 2, 3, 4])>>>np.average(data)2.5>>>np.average(np.arange(1,11),weights=np.arange(10,0,-1))4.0
>>>data=np.arange(6).reshape((3,2))>>>dataarray([[0, 1], [2, 3], [4, 5]])>>>np.average(data,axis=1,weights=[1./4,3./4])array([0.75, 2.75, 4.75])>>>np.average(data,weights=[1./4,3./4])Traceback (most recent call last):...TypeError:Axis must be specified when shapes of a and weights differ.
With
keepdims=True, the following result has shape (3, 1).>>>np.average(data,axis=1,keepdims=True)array([[0.5], [2.5], [4.5]])
>>>data=np.arange(8).reshape((2,2,2))>>>dataarray([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])>>>np.average(data,axis=(0,1),weights=[[1./4,3./4],[1.,1./2]])array([3.4, 4.4])>>>np.average(data,axis=0,weights=[[1./4,3./4],[1.,1./2]])Traceback (most recent call last):...ValueError:Shape of weights must be consistentwith shape of a along specified axis.