• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:17 mins read
You are currently viewing Python NumPy Array mean() Function

NumPy array mean() function in Python is used to compute the arithmetic mean or average of the array elements along with the specified axis or multiple axis. It is part of the NumPy library, which is widely used for numerical operations in Python. You get the mean by calculating the sum of all values in a Numpy array divided by the total number of values.

Advertisements

By default, the average is taken from the flattened array (from all array elements), otherwise along with the specified axis. When an input is an integer array, it returns Float 64 intermediate but you can change this behavior by specifying the return data type.

In this article, I will explain numpy.mean() function syntax, usage, and how to calculate the mean for the given single-dimensional or multi-dimensional array.

1. Quick Examples of NumPy Array mean() Function

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


# Quick examples of numpy array mean() function

# Example 1: Calculate the mean of the 1D array
arr = np.array([2, 7, 5, 8, 9, 4])
arr1 = np.mean(arr)

# Example 2: Calculate the arithmetic mean of the 2D array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])
arr1 = np.mean(arr)

# Example 3: Calculate the mean along axis 0 (columns)
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])
arr1 = np.mean(arr, axis=0)

# Example 4: Calculate the mean along axis 1 (rows)
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])
arr2 = np.mean(arr, axis = 1)

# Example 5: Get the mean values of an array 
# Along multiple-axis
arr = np.array([[[5, 8, 3], [9, 4, 2]], [[3, 9, 5], [2, 6, 8]]])
arr1 = np.mean(arr, axis=(0, 1))

# Example 6: Get the mean value of an array 
# With specified datatype
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])
arr1 = np.mean(arr, dtype = np.float32)

# Example 7: Get the mean of arr float64 data
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])
arr2 = np.mean(arr, dtype = np.float64)

2. Syntax of NumPy Array mean()

Following is the syntax of the numpy.mean() function.


# Syntax numpy.mean() 
numpy.mean(arr, axis=None, dtype=None, out=None, keepdims=<no value>)

2.1 Parameters of mean()

  • arr – Input array or object whose mean is to be computed.
  • axis – [ int or tuples of int] This parameter defines the axis along which the means are computed. By default, the mean is computed of the flattened array. If this is a tuple of ints, the mean is performed over multiple axes, instead of a single axis or all the axes as before.
  • dtype – Type to be used during the calculation of the arithmetic mean. For integer inputs, the default is float64.
  • out – Alternate output array in which to place the result. It must have the same shape as the expected output but the type (of the output) will be cast if necessary.
  • keepdims – If this is set to True, the axes that are reduced are left in the result as dimensions with size one.

2.2 Return Value of mean()

It returns the arithmetic mean of the array (a scalar value if the axis is none) or array with mean values along the specified axis.

3. Usage of NumPy mean() Function

The arithmetic mean is indeed calculated as the sum of array elements along a specified axis divided by the number of elements along that axis. The mean() function returns the arithmetic mean along with the specified axis of array elements.

The numpy.mean() function encapsulates this process. It provides the flexibility to calculate the mean along different axes in multidimensional arrays or over the entire flattened array, and it allows you to specify the data type of the result.

3.1 Get the Arithmetic Mean of 1D Array

You can get the arithmetic mean of a 1D array using the numpy.mean() function. For instance, arr is a 1D NumPy array containing the values [2, 7, 5, 8, 9, 4]. The numpy.mean() function is then applied to calculate the arithmetic mean of the elements in the 1D array, and the result is stored in the variable arr1. Finally, the mean value is printed on the console.


# Import numpy
import numpy as np

# Create a 1D array
arr = np.array([2, 7, 5, 8, 9, 4])
print("Original array:",arr)

# Calculate the mean of 1-D array
arr1 = np.mean(arr)
print("Arithmetic Mean of 1D array:",arr1)

Yields below output.

numpy array mean

4. Get the Arithmetic Mean of a 2D Array

You can also get the arithmetic mean of a 2D array using the numpy.mean() function. For instance, arr is a 2D NumPy array. The numpy.mean() function is applied without specifying the axis parameter, which means the mean will be calculated over the flattened array. The result is stored in the variable arr1, and it represents the arithmetic mean of all elements in the 2D array.


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

# Calculate the arithmetic mean of 2D array
arr1 = np.mean(arr)
print("Arithmetic Mean of 2D array:\n",arr1)

Yields below output.

numpy array mean

5. Get the Mean Values of the 2D NumPy Array along Axis

To get the mean values of a 2D NumPy array along a specific axis, you can use the numpy.mean() function with the axis parameter.

In the below example, arr is a 2D NumPy array. The numpy.mean() function is used to calculate the mean along axis 0 (columns) and axis 1 (rows). The results are stored in the variables arr1 and arr2. The arr1 array contains the mean values along axis 0 (columns), and the arr2 array contains the mean values along axis 1 (rows). Adjust the axis parameter based on your specific requirements.


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

# Calculate the mean along axis 0 (columns)
arr1 = np.mean(arr, axis=0)
print("Mean along axis 0 (columns):\n",arr1)

# Output:
# Original 2D array:
#  [[5 8 3 7]
#  [9 4 2 6]]
# Mean along axis 0 (columns):
#  [7.  6.  2.5 6.5]

# Calculate the mean along axis 1 (rows)
arr2 = np.mean(arr, axis = 1)
print("Mean along axis 1 (rows):\n",arr2)

# Output:
# Mean along axis 1 (rows):
#  [5.75 5.25]

6. Get the Mean Values of the 3D Array along Multiple Axis

To create a 3-dimensional array using NumPy and calculate the arithmetic mean along multiple axes using np.mean() with the axis parameter.

In the below example, you can calculate the arithmetic mean along both axis 0 and axis 1, resulting in a 1D array containing the mean values for each element along the third axis.


# Create 3-D array
arr = np.array([[[5, 8, 3], [9, 4, 2]], [[3, 9, 5], [2, 6, 8]]])
# Get the mean values of an array along multiple axis
arr1 = np.mean(arr, axis=(0, 1))
print(arr1)

# Output:
# [4.75 6.75 4.5 ]

7. Use Datatype Param

To create a 2D array using NumPy and calculate the arithmetic mean with a specified data type using np.mean() with the dtype parameter. The dtype parameter is used to specify the data type of the result. In this case, it’s set to np.float32.


# Create 2D array
arr = np.array([[5, 8, 3, 7], [9, 4, 2, 6]])

# Get the mean value of an array 
# With specified datatype
arr1 = np.mean(arr, dtype = np.float32)
print("Arithmetic Mean of the array:",arr1)

# Output:
# Arithmetic Mean of the array: 5.5

Similarly, to create a 2D array using NumPy and calculate the arithmetic mean with a specified data type (np.float64) using np.mean() with the dtype parameter. You can calculate the arithmetic mean with the specified data type (np.float64).


# Get the mean of arr float64 data
arr2 = np.mean(arr, dtype = np.float64)
print("Arithmetic Mean of the array:",arr2)

# Output:
# Arithmetic Mean of the array: 5.5

Frequently Asked Questions

What does the numpy.mean() function do?

numpy.mean() computes the arithmetic mean (average) of elements along a specified axis in a NumPy array. It can be used to calculate the mean of a whole array or along a particular axis in multidimensional arrays.

Can I calculate the mean along a specific axis in a 2D array?

You can calculate the mean along a specific axis in a 2D array using the numpy.mean() function. The axis parameter allows you to specify the axis along which the mean should be calculated.

What happens if I don’t specify the axis parameter?

If you don’t specify the axis parameter when using the numpy.mean() function, the default behavior is to compute the mean over the flattened array. The flattened array is a 1D representation of the input array obtained by concatenating the rows of the array.

Can I specify the data type of the result?

You can specify the data type of the result using the dtype parameter in the numpy.mean() function. The dtype parameter allows you to force the data type of the output to a specific type.

How do I compute the mean of a flattened array?

To compute the mean of a flattened array using numpy.mean(), you can use the ravel() function to flatten the array and then apply the numpy.mean() function

Conclusion

In this article, I have explained ned how to calculate the arithmetic mean of NumPy array along with the specified axis and multiple axes. Also explained how to use dtype optional param to change the return data type.

Happy Learning!!

References