NumPy Average

The Python NumPy array library uses the numpy.average() method for computing the weighted average of a NumPy n-dimensional array along the specified axis.

The average in linear algebra is the proportion of the sum of a given set of values to the total number of values according to their weightage.

NumPy average() Syntax

The Syntax of numpy.average() method is:

numpy.average(
    array_name, axis=axis_type, weights=array_like, returned=bool, keepdims=bool
)

NumPy average Parameters

  • array_name: the name of the input array
  • axis: None or int or tuple of ints (optional) – the alignment or axis of the average is to be computed
  • weights: array_like (optional) – An array of weights with respect to the input array. The values in the input array will average according to the respective weightage. If the weight parameter weights = None, then all the weightage of input array values are equated to one.
  • returned: bool (optional) – The default value is False. If the value is True, the tuple(average, sum_of_weights) is returned, else only the average is returned.
  • keepdims: bool (optional) – If the value of keepdims is set to True, then the axes that are reduced will be left in the result as dimensions with size one.
Note: The calculation for average is as follows:
average = sum(array_name * weights)/sum(weights)

NumPy average() Return Value :

numpy.average() method returns the average along the specified axis. If returned = True, then a tuple with the average as the first element and sum_of_weights as the second element is returned.

  • float64 average if parameter returned = False,
  • tuple(average, sum_of_weights) is returned if returned = True.

Raises

  • ZeroDivisionError: When all weights along the axis are zero.
  • TypeError: When the length of 1D weights is not the same as the shape of arr along axis.

Example 1: NumPy average() of an Array values

numpy.average() will compute the weighted average of a numpy n-dimensional array array_in input array.

# import numpy to be used as np
import numpy as np

# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)

print("The input array of values:\n\n", array_in, "\n")

# average is calculated with default as flattened
average_final = np.average(array_in)

print(
    "The average and type of the output average are:\nAverage =",
    average_final,
    ",\nType of Output =",
    type(average_final),
)

Output

The input array of values:

 [[[ 0  1]
  [ 2  3]
  [ 4  5]
  [ 6  7]
  [ 8  9]]

 [[10 11]
  [12 13]
  [14 15]
  [16 17]
  [18 19]]] 

The average and type of the output average are:
Average = 9.5 ,
Type of Output = <class 'numpy.float64'>

 Example 2: NumPy average() of an array values in column-wise

When the axis parameter is specified as axis = 0, then the column-major order will be called off for average calculation.

# import numpy to be used as np
import numpy as np

# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)

print("The input array of values:\n\n", array_in, "\n")

# average is calculated with default as flattened
average_final = np.average(array_in, axis=0)

print(
    "The average column-major and type of the output average are:\nAverage =\n",
    average_final,
    ",\nType of Output =",
    type(average_final),
)

Output

The input array of values:

 [[[ 0  1]
  [ 2  3]
  [ 4  5]
  [ 6  7]
  [ 8  9]]

 [[10 11]
  [12 13]
  [14 15]
  [16 17]
  [18 19]]] 

The average column-major and type of the output average are:
Average =
 [[ 5.  6.]
 [ 7.  8.]
 [ 9. 10.]
 [11. 12.]
 [13. 14.]] ,
Type of Output = <class 'numpy.ndarray'>

 Example 3 : NumPy average() of an array values in row-wise

When the axis parameter is specified as axis = 1, then the row-major order will be called off for average calculation.

# import numpy to be used as np
import numpy as np

# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)

print("The input array of values:\n\n", array_in, "\n")

# average is calculated with default as flattened
average_final = np.average(array_in, axis=1)

print(
    "The average row-major and type of the output average are:\nAverage =\n",
    average_final,
    ",\nType of Output =",
    type(average_final),
)

Output

The input array of values:

 [[[ 0  1]
  [ 2  3]
  [ 4  5]
  [ 6  7]
  [ 8  9]]

 [[10 11]
  [12 13]
  [14 15]
  [16 17]
  [18 19]]] 

The average row-major and type of the output average are:
Average =
 [[ 4.  5.]
 [14. 15.]] ,
Type of Output = <class 'numpy.ndarray'>

Example 4 : NumPy average of an array values with returned type as a tuple of average and sum_of_weights

When the parameter returned is specified as returned = True, then the output of the average function will be a tuple of average and sum_of_weights like as (average, sum_of_weights).

# import numpy to be used as np
import numpy as np

# initialize the input array
array_in = np.arange(20).reshape(2, 5, 2)

# initialize the weighted array
weights_array = np.arange(20).reshape(2, 5, 2)

print("The input array is:\n\n", array_in, "\n")
print("The weighted array is:\n\n", weights_array)

# average with returned value as True
average_array = np.average(array_in, axis=1, weights=weights_array, returned=True)
print(
    "\nThe tuple of arrays of average and sum_of_weights are as elements:\n\n",
    average_array,
    "\n",
)

# the output object is a tuple of (average, sum_of_weights)
print("\nThe type of output object is:\n\n", type(average_array))

# average array only
print("\nAverage array is:\n\n", average_array[0], "\n")

# sum_of_weights array only
print("\nsum_of_weights array is:\n\n", average_array[1])

Output

The input array is:

 [[[ 0  1]
  [ 2  3]
  [ 4  5]
  [ 6  7]
  [ 8  9]]

 [[10 11]
  [12 13]
  [14 15]
  [16 17]
  [18 19]]] 

The weighted array is:

 [[[ 0  1]
  [ 2  3]
  [ 4  5]
  [ 6  7]
  [ 8  9]]

 [[10 11]
  [12 13]
  [14 15]
  [16 17]
  [18 19]]]

The tuple of arrays of average and sum_of_weights are as elements:

 (array([[ 6.        ,  6.6       ],
       [14.57142857, 15.53333333]]), array([[20., 25.],
       [70., 75.]])) 


The type of output object is:

 <class 'tuple'>

Average array is:

 [[ 6.          6.6       ]
 [14.57142857 15.53333333]] 


sum_of_weights array is:

 [[20. 25.]
 [70. 75.]]

Conclusion

The average of a NumPy array can be computed using the NumPy method, numpy.average(). The return type will be a float64 if the keyword returned = False, else a tuple of elements average and sum_of_wights is returned.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python List Index()

Python List index()

Table of Contents Hide Syntax of List index() index() ParametersReturn Value from List index()Example 1: Find the index of the elementExample 2: Index of the Element not Present in the List…
View Post
Python Type()

Python type()

Table of Contents Hide type() Syntaxtype() Parameterstype() Return ValueDifference between type() function and isinstance() functionExample of isinstance() method in PythonExample 1: Finding the type of a Python objectExample 2: type()…
View Post
Python List Extend()

Python List extend()

Table of Contents Hide Syntax of List extend() extend() ParametersReturn Value from List extend()Difference between append() and extend() method in PythonExample 1: How to use List extend() MethodExample 2: Add Elements…
View Post