• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:19 mins read
You are currently viewing How to Compute Average Of NumPy Array?

NumPy average() function is used to compute the weighted average along the specified axis. This is a statistical function used to calculate the weight mean along the specified axis. Without weights parameter average() will behave same as NumPy mean() function.

In this article, I will explain average() syntax, parameters, and how to get the average of the total number of elements of the NumPy array, or along some axis, you can also calculate a weighted average of elements.

1. Quick Examples of NumPy Average

If you are in a hurry, below are some quick examples of how to calculate the average of an array by using the NumPy average() function.


# Quick examples of numpy average 

# Example 1: Get the average of 2-D array
arr = np.array([[6, 8, 4],[ 9, 5, 7]]) 
arr2 = np.average(arr) 

# Example 2: Calculate the weighted average
weights = np.array([[1, 2, 3],[4, 5, 6]])
arr2 = np.average(arr, weights=weights)

# Example 3: Get the average of array 
# Along axis = 0
arr2 = np.average(arr, axis=0) 

# Example 4: Get the average of array 
# Along axis = 1
arr2 = np.average(arr, axis=1) 

# Example 5: Get the average with weights 
# To average along axis = 0
arr2 = np.average(arr, axis=0, weights=[0.3,0.7])

# Example 6: Get the average with weights 
# To average along axis = 1 
arr2 = np.average(arr, axis=1, weights=[0.3,0.7,0.8])

# Example 7: Get the average of array 
# Along with weights, axis = 1,& returned
arr2 = np.average(arr, axis=1, weights=[0.3,0.7,0.8], returned = True)

2. Syntax of NumPy average()

Following is the syntax of the average() function.


# Syntax of NumPy average()
numpy.average(arr, axis=None, weights=None, returned=False)

2.1 Parameters of average()

Below are the parameters of the average() function.

  • arr – This is the input array for which you want to compute the average.
  • axis – int or None or tuple of ints(optional) Axis or axes along which to average arr. By default, the axis is set to None, which will calculate the average of all the elements of the source array.
  • weights – This parameter defines an array containing weights associated with the values in arr. Each value in arr contributes to the average according to its associated weight. The weighted array can be one-dimensional or of the same shape as the input array. Average=sum(arr*weights)/sum(weights)
  • returned – By default, this parameter is set to False. If you set it as True, then a tuple of average and sum_of_weights is returned. If it is False, the average is returned. If weights=None, a sum of weights is equivalent to the number of elements over which the average is taken.

2.2 Return Value of average()

It returns the average of elements in an array if the returned parameter is set to False. If it is set to True it returns both the average and the sum of weights.

3. Usage of NumPy average() Function

NumPy average() function is a statistical function for calculating the average of a total number of elements in an array, or along a specified axis, or you can also calculate the weighted average of elements in an array. Note that the average is used to calculate the standard deviation of the NumPy array.

Let’s create a 2-dimensional array and then calculate the average (mean) of all the elements in that array. Here, a 2-dimensional NumPy array is created using the np.array() function. The array is assigned to the variable arr. The array has two rows and three columns, with the values provided in the nested lists. The np.average() function is used to calculate the average (mean) of all the elements in the 2D array arr. The result is stored in the variable arr2.


# Import numpy
import numpy as np

# Create 2-D NumPy array
arr = np.array([[6, 8, 4],[ 9, 5, 7]]) 
print("Original 2D array:\n", arr)

# Get the average of 2-D array
arr2 = np.average(arr) 
print("Average of 2D array:",arr2)

Yields below output.

numpy average

You can use the numpy.average() function to calculate the weighted average. The weights parameter in this function allows you to specify an array of weights corresponding to each element in the array. For instance, to create a 2D array weights, which should have the same shape as the arr array. Each element in the weights array corresponds to a weight for the corresponding element in the arr array.

Here, the np.average() function is used to calculate the weighted average of all elements in the arr array using the weights provided in the weights array. The resulting value is stored in the variable arr2, and it represents the weighted average of the entire array.


# Create 2-D NumPy array
arr = np.array([[6, 8, 4],[ 9, 5, 7]]) 
print("Original 2D array:\n", arr)

# Sample weights
weights = np.array([[1, 2, 3],[4, 5, 6]])

# Calculate the weighted average
arr2 = np.average(arr, weights=weights)
print("Weighted Average:",arr2)  

Yields below output.

numpy average

4. Get the Average of 2D Array along with Axis

In order to find out the average of an array along with an axis you need to pass the axis parameter to the function. To find the average values of each column use axis=0, and to get the average values of each row use axis=1. You can specify the axis of interest using the axis parameter.

In the below example, create a 2-dimensional array and then calculate the average values along columns (axis=0) of that array. Here, a 2-dimensional NumPy array is created using the np.array() function, and it is assigned to the variable arr. The array has two rows and three columns, with the values provided in the nested lists. then the np.average() function is used to calculate the average along columns (axis=0). The result is an array containing the averages for each column.


# Get the average values over row 
# For each of 3 columns 
arr2 = np.average(arr, axis=0) 
print("Average along columns:\n",arr2)

# Output:
Average along columns:
 [7.5 6.5 5.5]

Similarly, to create a 2-dimensional array and then calculate the average values along rows (axis=1) of that array. Here, a 2-dimensional NumPy array is created using the np.array() function, and it is assigned to the variable arr. The array has two rows and three columns, with the values provided in the nested lists. then the np.average() function is used to calculate the average along rows (axis=1). The result is an array containing the averages for each row.


# Get the average values over column
# for each of 2 rows
arr2 = np.average(arr, axis=1)  
print("Average along rows:\n",arr2)

# Output:
# Average along rows:
# [6. 7.]

5. Average with Axis & Weights

When you specify the weights parameter in the np.average() function, it multiplies each element in the array by its corresponding weight before calculating the average. The weighted average is then computed as the sum of the products of the elements and their weights, divided by the sum of the weights.

The weights parameter allows for more flexibility in assigning importance to different elements when computing averages. This is particularly useful in scenarios where certain values should contribute more or less to the overall average based on their significance.


# Calculate the weighted average along axis 0 (columns)
arr2 = np.average(arr, axis=0, weights=[0.3,0.7])
print("Weighted average along columns:\n",arr2)

# Output:
# Weighted average along columns:
#  [8.1 5.9 6.1]

# Get the average of array along with weights and axis = 1
arr2 = np.average(arr, axis=1, weights=[0.3,0.7,0.8])
print("Weighted average along rows:\n",arr2)

# Output:
# Weighted average along rows:
#  [5.88888889 6.55555556]

6. Using Axis, Weights & Returned

Set returned parameter to True and pass along with axis and weights to the average() function, this will compute the average of the given array and will return the tuple of the average and sum of weights


# Get the average of array along with weights, axis = 1,& returned
arr2 = np.average(arr, axis=1, weights=[0.3,0.7,0.8], returned = True)
print("Weighted average along rows:\n",arr2)

# Output:
# Weighted average along rows:
# (array([5.88888889, 6.55555556]), array([1.8, 1.8]))

Frequently Asked Questions

What does np.average() do in NumPy?

The np.average() function in NumPy is used to calculate the weighted average or arithmetic mean of an array along a specified axis. It can take into account user-defined weights for each element in the array.

How do I calculate the simple mean with np.average()?

To calculate the simple mean (arithmetic mean) with np.average(), you can simply use the function without specifying the weights parameter. For example, the np.average() function is applied to the array data without providing any weights.

How do I calculate the weighted average?

To calculate the weighted average using np.average(), you can provide an array of weights using the weights parameter. The weighted average is computed by multiplying each element by its corresponding weight, summing these products, and then dividing by the sum of the weights.

How do I calculate the average along a specific axis?

To calculate the average along a specific axis using np.average(), you can use the axis parameter. The axis parameter allows you to specify the axis along which the average is calculated.

What does the returned parameter do?

The returned parameter in np.average() is an optional parameter that, when set to True, causes the function to return a tuple containing both the average and the sum of weights (if weights are specified). If returned is set to False or not specified, the function only returns the average.

Can I calculate the average of an entire array without specifying an axis?

You can calculate the average of an entire array without specifying an axis by using np.average() without the axis parameter. When axis is not specified or set to None, the function calculates the average over all elements in the array.

Conclusion

In this article, I have explained the syntax and usage of numpy.average() function which calculates the average of elements, along some axis. Also covered calculating a weighted average of elements with examples.

Happy Learning!!

References

Vijetha

Vijetha is an experienced technical writer with a strong command of various programming languages. She has had the opportunity to work extensively with a diverse range of technologies, including Python, Pandas, NumPy, and R. Throughout her career, Vijetha has consistently exhibited a remarkable ability to comprehend intricate technical details and adeptly translate them into accessible and understandable materials. Follow me at Linkedin.