NumPy | average method
Start your free 7-days trial now!
Numpy's average(~) method computes the weighted average along the specified axis.
Parameters
1. a | array-like
The input array.
2. axis | None or int or tuple of int | optional
The axis along which to compute the mean.
Axis | Meaning |
|---|---|
0 | Row-wise computation of mean |
1 | Column-wise computation of mean |
None | All values used to compute the mean |
3. weights | axis | optional
The array containing the weights. The dimension must be 1D with size equal to that of a, or the exact same shape as a. By default, weights=None, that is, a simple mean will be computed.
4. return | boolean | optional
Whether you want the sum of weights returned. By default return=False.
Return value
If axis in unset, then a scalar is returned. Otherwise, a Numpy array of weighted averages is returned.
Examples
Basic usage
Consider the following:
a = np.array([1,2,3])np.average(a, weights=[0,2,4])
2.6667
Here, the weighted average is:
(1*0 + 2*2 + 3*4) / (0+2+4) = 2.6667
Getting the sum of the weighted average
To get the sum of the weighted used (i.e. 0+2+4=6), set returned=True:
np.average([1,2,3], weights=[0,2,4], returned=True)
(2.6666666666666665, 6.0)
Computing the weighted average of a 2D array
Suppose we have the following 2D array:
a = np.array([[1,2],[3,4]])a
array([[1, 2], [3, 4]])
Weighted average of all values
Computing the weighted average of all values:
np.average(a, weights=[[5,6],[7,8]])
2.6923076923076925
Weighted average of each column
Computing the weighted average of each column, set axis=0:
np.average(a, weights=[[5,6],[7,8]], axis=0)
array([2.16666667, 3.14285714])
Weighted average of each row
Computing the weighted average of each row, set axis=1:
np.average(a, weights=[[5,6],[7,8]], axis=1)
array([1.54545455, 3.53333333])