NumPy – Using ndarray.mean() method (4 examples)

Updated: March 1, 2024 By: Guest Contributor Post a comment

Introduction

NumPy, a fundamental package for numerical computation in Python, offers a plethora of functionalities for manipulating arrays. One key method, ndarray.mean(), computes the mean (average) value of an array. This tutorial delves into using the ndarray.mean() method through four illustrative examples, escalating from basic to more advanced use cases.

Syntax & Parameters

Syntax:

ndarray.mean(axis=None, dtype=None, out=None, keepdims=False)

Parameters:

  • axis: {None, int, tuple of ints}, optional. Axis or axes along which the means are computed. The default (axis=None) is to compute the mean of the flattened array.
  • dtype: data-type, optional. The type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.
  • out: ndarray, optional. Alternate output array in which to place the result. It must have the same shape as the expected output but the type will be cast if necessary.
  • keepdims: bool, optional. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original array.

Returned values:

  • mean: ndarray or scalar. If out=None, returns a new array containing the mean values, otherwise a reference to the output array is returned.

Example 1: Basic Mean Calculation

Let’s start by calculating the mean of a simple one-dimensional array.

import numpy as np

# Creating a one-dimensional array
array_1d = np.array([2, 4, 6, 8, 10])

# Calculating the mean
mean_value = array_1d.mean()

print(f'Mean value: {mean_value}')

Output:

Mean value: 6.0

This example shows the straightforward approach to calculating the mean of a numeric array using NumPy.

Example 2: Mean Across Different Axes

In multidimensional arrays, mean can be computed along specific axes. This addresses more complex structures and accumulates values directionally.

import numpy as np

# Creating a two-dimensional array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Calculating the mean across each column (axis=0)
mean_col = array_2d.mean(axis=0)

# Calculating the mean across each row (axis=1)
mean_row = array_2d.mean(axis=1)

print(f'Mean value across columns: {mean_col}')
print(f'Mean value across rows: {mean_row}')

Output:

Mean value across columns: [4. 5. 6.]
Mean value across rows: [2. 5. 8.]

This allows for flexibility in analyzing data, whether you want insights into each feature (column) or each observation (row).

Example 3: Mean with Floating-Point Precision

When dealing with floating-point numbers, ensuring precision is important. Here, we calculate the mean of an array containing floating-point numbers and demonstrate how to format the output.

import numpy as np

# Creating an array with floating-point numbers
float_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5])

# Calculating the mean
mean_float = float_array.mean()

print(f'Mean with floating points: {mean_float:.2f}')

Output:

Mean with floating points: 3.30

This exemplifies maintaining precision in mathematical calculations, crucial for scientific computation and data analysis.

Example 4: Weighted Mean Calculation

Beyond the simple mean, NumPy can compute the weighted mean, adding significance to certain values over others. This requires the use of numpy.average() rather than ndarray.mean(), but it is important to understand as an advanced concept.

import numpy as np

# Creating an array
values = np.array([1, 2, 3, 4, 5])
# Defining weights
weights = np.array([0.1, 0.1, 0.4, 0.2, 0.2])

# Calculating the weighted mean
weighted_mean = np.average(values, weights=weights)

print(f'Weighted mean: {weighted_mean}')

Output:

Weighted mean: 3.3

This method lends greater control over how data elements impact the overall mean, invaluable in diverse analytical situations.

Conclusion

In sum, the ndarray.mean() method in NumPy serves as a versatile tool for computing averages in your array data. Whether you’re working with simple lists, multidimensional arrays, floating-point precision, or weighted elements, understanding these examples can significantly enhance your data analysis skills.