Using ndarray.min() method in NumPy (5 examples)

Updated: February 26, 2024 By: Guest Contributor Post a comment

The Fundamentals

NumPy is a fundamental package for scientific computing with Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. One of the essential methods provided by NumPy is ndarray.min(), which is used to find the minimum value in an array.

Syntax:

numpy.ndarray.min(axis=None, keepdims=False, initial=None)

Parameters:

  • axis (int or tuple of ints, optional): Axis or axes along which to operate. By default, None is used, which means the minimum value is computed over the entire array. If specified, the function will compute the minimum along the specified axis or axes. If the input is a 2D array, specifying axis=0 will compute the minimum value along the columns, and axis=1 will compute it along the rows. To compute the minimum over multiple axes simultaneously, provide a tuple of axis numbers.
  • keepdims (bool, optional): If 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. Default is False.
  • initial (scalar, optional): The maximum value to start with. If not specified, the initial value is set to the first element along the specified axis.

Returns:

  • If axis is None: Returns the minimum value from the entire array.
  • If axis is an integer: Returns a 1D array containing the minimum values along the specified axis.
  • If axis is a tuple of integers: Returns an array with the minimum values computed over the specified axes.

This article explains how to use the ndarray.min() method in NumPy through five progressive examples, ranging from basic usage to more advanced applications.

Example 1: Basic Usage of ndarray.min()

Let’s start with the basics. The simplest use case of the ndarray.min() method is to find the minimum element in a one-dimensional array.

import numpy as np

arr = np.array([2, 3, 1, 4, 5])
min_value = arr.min()
print("Minimum value:", min_value)

Output: Minimum value: 1

This example demonstrates how to find the minimum value in a simple array.

Example 2: Specifying the Axis

In multidimensional arrays, the ndarray.min() method can compute the minimum values along a specific axis. This feature is particularly useful when dealing with matrices or higher-dimensional data.

import numpy as np

arr = np.array([[2, 3, 1], [4, 5, 6]])
min_value_row = arr.min(axis=0)
print("Minimum values across rows:", min_value_row)
min_value_column = arr.min(axis=1)
print("Minimum values across columns:", min_value_column)

Output:

Minimum values across rows: [2 3 1]
Minimum values across columns: [1 4]

This example displays how to compute minimum values across different axes of a 2-dimensional array.

Example 3: Working with NaN Values

One common issue in data analysis is dealing with NaN (Not a Number) values. Fortunately, NumPy provides a handy way to ignore these values while computing the minimum.

import numpy as np

arr = np.array([2, np.nan, 3, 1, np.nan])
min_value = np.nanmin(arr)
print("Minimum value ignoring NaNs:", min_value)

Output: Minimum value ignoring NaNs: 1

This example demonstrates the use of the np.nanmin() function to calculate the minimum value while ignoring NaNs in the array.

Example 4: Minimum Value in a Structured Array

NumPy’s structured arrays allow for arrays of mixed data types. Finding the minimal element in such an array might require specifying the field name.

import numpy as np

dtype = [('name', 'S10'), ('age', int)]
values = [(b'Alan', 35),(b'Eve', 29),(b'John', 23)]
arr = np.array(values, dtype=dtype)
min_age = np.min(arr['age'])
print("Minimum age:", min_age)

Output: Minimum age: 23

This example showcases how to find the minimum element in a specific field of a structured array.

Example 5: Combining min() with Other NumPy Methods

Lastly, we explore how the ndarray.min() method can be combined with other NumPy functionality to perform more complex operations, such as filtering an array before finding its minimum value.

import numpy as np

arr = np.array([2, 3, 1, 4, 5])
filtered_arr = arr[arr % 2 == 0]  # Get even elements
min_value = filtered_arr.min()
print("Minimum even value:", min_value)

Output: Minimum even value: 2

This advanced example demonstrates how to apply a filter to an array and then find the minimum value among the elements that meet the condition.

Conclusion

The ndarray.min() method is a versatile tool within NumPy that allows you to efficiently find minimum values across arrays of various complexities. Whether working with simple, multidimensional, or structured data, understanding how to leverage this function can significantly streamline your data analysis and manipulation tasks.