numpy.average()
The numpy.average()
function in NumPy computes the weighted average of a given array. It can also perform a simple average of all elements in the given array if an optional weight array is not provided.
Syntax
The syntax for numpy.average()
function is as follows:
numpy.average(a, axis=None, weights=None, returned=False)
Here,
a
: Input array which needs to be averaged along a particular axis.axis
: Axis along which the average will be computed. The default is None, which means the average is computed over all elements in the input array.weights
: An optional array of scalar weights to apply to each element in the input array to compute the weighted average.returned
: If set to True, returns the average and the sum of weights used to compute the average.
Example
import numpy as np
# Create an input array
a = np.array([2, 4, 6, 8, 10])
# Print the weighted average of the input array
print("Weighted average of input array: ", np.average(a, weights=[1, 2, 3, 4, 5]))
# Print the simple average of the input array
print("Simple average of input array: ", np.average(a))
Output
Weighted average of input array: 6.666666666666667
Simple average of input array: 6.0
Explanation
In the above example, a NumPy array "a" is created and weighted average as well as simple average of the array values are calculated using numpy.average()
function.
In the first print statement, the weighted average of the input array is calculated by passing the weights
parameter as a list of scalar integer values.
In the second print statement, the simple average of the input array is calculated as no weights
parameter is passed.
Use
The numpy.average()
function is useful in scenarios where we need to calculate the average of numerical values in an array while also accounting for the relative importance of each value.
Important Points
- If the
weights
argument is not provided, all of the values in the input array will be given equal weight. - The returned type of
numpy.average()
is always a float value. - Use
axis
parameter to compute the average along a specific axis of a multi-dimensional input array.
Summary
In summary, numpy.average()
function is used to calculate the weighted or simple average of numerical values in an array, with the ability to specify relative weights for each value in the input array. numpy.average()
is a useful function in data science and machine learning, where weighted averages are often used to compute metrics such as precision and recall.