Unlocking the Power of Min() Function

The min() function is a powerful tool in the world of arrays, allowing you to extract the smallest element with ease. But what makes it tick? Let’s dive into the syntax and explore its capabilities.

Syntax Breakdown

The min() function takes six arguments:

  • array: the input array
  • axis (optional): the axis along which the minimum value is returned (int)
  • out (optional): the array to store the output
  • keepdims (optional): whether to preserve the input array’s dimension (bool)
  • initial (optional): the minimum value of an output element (scalar)
  • where (optional): elements to include in the minimum value calculation (array of bool)

Return Value: The Smallest Element

The min() function returns the smallest element in the array. But be aware: if at least one element is NaN (Not a Number), the function will return NaN.

Handling 2D Arrays with Axis

When working with 2D arrays, the axis argument is crucial. It defines how to handle the smallest element:

  • axis = None: the array is flattened, and the minimum of the flattened array is returned
  • axis = 0: the smallest element in each column is returned
  • axis = 1: the smallest element in each row is returned
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.min(arr, axis=0))  # Output: [1 2 3]
print(np.min(arr, axis=1))  # Output: [1 4]

Storing Results with Out

Instead of generating a new output array, you can use the out argument to store the result in a desired location.

import numpy as np

arr = np.array([1, 2, 3])
result = np.empty(1)
np.min(arr, out=result)
print(result)  # Output: [1]

Preserving Dimensions with Keepdims

When keepdims = True, the resulting array matches the dimension of the input array. Otherwise, the result is a one-dimensional array of smallest numbers.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.min(arr, axis=0, keepdims=True))  # Output: [[1 2 3]]
print(np.min(arr, axis=0, keepdims=False))  # Output: [1 2 3]

Defining Maximum Values with Initial

The initial argument allows you to set the maximum value np.min() can return. If the minimum value of the array is larger than the initial value, the initial value is returned.

import numpy as np

arr = np.array([5, 6, 7])
print(np.min(arr, initial=10))  # Output: 5
print(np.min(arr, initial=3))  # Output: 3

Selective Calculation with Where

The where argument specifies elements to include in the calculation of the minimum value. This feature gives you precise control over your results.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
mask = np.array([True, False, True, False, True])
print(np.min(arr, where=mask))  # Output: 1

Leave a Reply