numpy.min(a, axis=None, out=None, keepdims=False, initial=None, where=True) returns the minimum value of an array or minimum values along a specified axis. Both the standalone function np.min() and the array method ndarray.min() evaluate identical aggregation parameters.Reducing along an axis removes that dimension by default unless keepdims=True is specified. When filtering elements with where, an explicit initial ceiling must be provided. For arrays containing missing data, standard min() propagates NaN, whereas nanmin() computes minimums over remaining numerical values.
| Parameter | Description |
|---|---|
a | Input array-like data containing elements to evaluate |
axis | Axis or tuple of axes along which the minimum is computed (default None reduces the entire array) |
out | Alternative output array to hold the result; must match expected reduction shape |
keepdims | When True, reduced axes are retained with length one for broadcast compatibility |
initial | Starting ceiling value for the reduction; acts as a competing comparison bound |
where | Boolean inclusion mask broadcastable to the input array |
min returns the lowest value among the included elements. It does not return its position; use argmin when an index position is needed. Use fixed values for repeatable testing or generate synthetic arrays with random.randint().
import numpy as np
def sample_array():
return np.array([[6, 3, 2], [7, 2, 2], [6, 2, 9]])
a = sample_array()
print(a)
assert a.shape == (3, 3)Expected output
[[6 3 2]
[7 2 2]
[6 2 9]]
With axis=None, min reduces all elements to one scalar. Setting axis=0 collapses across rows, yielding one minimum per column. Setting axis=1 collapses across columns, returning one minimum per row. For conceptual mechanics, review axis reduction.
a = sample_array()
print("Overall:", a.min())
print("Column minimums (axis=0):", a.min(axis=0))
print("Row minimums (axis=1):", a.min(axis=1))
assert a.min() == 2
assert np.array_equal(a.min(axis=0), np.array([6, 2, 2]))
assert np.array_equal(a.min(axis=1), np.array([2, 2, 2]))Expected output
Overall: 2
Column minimums (axis=0): [6 2 2]
Row minimums (axis=1): [2 2 2]
In square matrices, both axes return arrays of equal length. Using a rectangular matrix of shape (2, 4) makes shape transformations clear: axis=0 produces length 4, while axis=1 produces length 2.
rect = np.array([[10, 2, 30, 4], [5, 20, 7, 40]])
print("Shape:", rect.shape)
print("Axis 0 minimums:", rect.min(axis=0))
print("Axis 1 minimums:", rect.min(axis=1))
assert rect.min(axis=0).shape == (4,)
assert rect.min(axis=1).shape == (2,)Expected output
Shape: (2, 4)
Axis 0 minimums: [5 2 7 4]
Axis 1 minimums: [2 5]
The out destination must match the expected reduced shape and data type. For axis=0 on a (3, 3) matrix, preallocate an array of shape (3,). Preallocating buffers with zeros() eliminates repeated memory allocations inside production loops.
a = sample_array()
dest_col = np.zeros(3, dtype=int)
a.min(axis=0, out=dest_col)
print("Captured in dest_col:", dest_col)
assert np.array_equal(dest_col, np.array([6, 2, 2]))
dest_scalar = np.zeros((), dtype=int)
a.min(out=dest_scalar)
print("Captured 0D scalar:", dest_scalar)
assert int(dest_scalar) == 2Expected output
Captured in dest_col: [6 2 2]
Captured 0D scalar: 2
Without keepdims, reducing a 2D array produces a 1D vector. With keepdims=True, the reduced axis remains present with size 1, allowing direct subtraction or division across original arrays without manual reshaping.
a = sample_array()
kd_true = a.min(axis=1, keepdims=True)
kd_false = a.min(axis=1, keepdims=False)
print("keepdims=True shape:", kd_true.shape)
print("keepdims=False shape:", kd_false.shape)
print("Distance above row minimum:\n", a - kd_true)
assert kd_true.shape == (3, 1)
assert kd_false.shape == (3,)Expected output
keepdims=True shape: (3, 1)
keepdims=False shape: (3,)
Distance above row minimum:
[[4 1 0]
[5 0 0]
[4 0 7]]
The where argument accepts a Boolean mask indicating which elements to include. Because excluded cells may leave no valid candidates, NumPy requires an explicit initial upper-bound ceiling when where is supplied.
a = sample_array()
mask = np.array([True, False, True])
res = a.min(axis=1, where=mask, initial=10)
print("Masked row minimums (initial=10):", res)
assert np.array_equal(res, np.array([2, 2, 6]))Expected output
Masked row minimums (initial=10): [2 2 6]
The initial parameter is evaluated alongside all array elements. If initial is smaller than the observed minimum in the array, the final returned result will be the initial value itself.
a = sample_array()
print("Default min:", a.min())
print("With initial=12:", a.min(initial=12))
print("With initial=1 :", a.min(initial=1))
assert a.min(initial=12) == 2
assert a.min(initial=1) == 1Expected output
Default min: 2
With initial=12: 2
With initial=1 : 1
Calling min() on an empty array without an initial value raises a ValueError. Supplying initial defines the exact fallback value returned when no elements qualify:
empty_vec = np.array([], dtype=float)
try:
empty_vec.min()
except ValueError as e:
print("Caught expected error:", e)
fallback = empty_vec.min(initial=np.inf)
print("With initial=np.inf:", fallback)
assert np.isinf(fallback)Expected output
Caught expected error: zero-size array to reduction operation minimum which has no identity
With initial=np.inf: inf
Standard floating-point NaN values poison standard aggregations. Use np.nanmin() to skip missing values and return the smallest finite value:
data_with_nan = np.array([4.5, np.nan, 1.8, 9.2])
print("Standard min():", np.min(data_with_nan))
print("np.nanmin(): ", np.nanmin(data_with_nan))
assert np.isnan(np.min(data_with_nan))
assert np.nanmin(data_with_nan) == 1.8Expected output
Standard min(): nan
np.nanmin(): 1.8
While min() returns the value itself, argmin() returns the index position of the minimum. If multiple identical minimums exist, argmin() returns the first index encountered.
scores = np.array([88, 42, 95, 42, 70])
min_idx = np.argmin(scores)
print("First minimum index:", min_idx)
print("All tie locations: ", np.where(scores == scores.min())[0])
assert min_idx == 1Expected output
First minimum index: 1
All tie locations: [1 3]
Do not confuse the reduction function np.min() with the element-wise universal function np.minimum(). np.minimum() performs pairwise comparisons across two broadcast-compatible arrays:
arr_x = np.array([10, 20, 30])
arr_y = np.array([15, 12, 35])
pairwise_min = np.minimum(arr_x, arr_y)
print("Element-wise minimum:", pairwise_min)
assert np.array_equal(pairwise_min, np.array([10, 12, 30]))Expected output
Element-wise minimum: [10 12 30]
In 3D arrays of shape (batch, rows, cols), passing a tuple of axes such as axis=(1, 2) collapses spatial slices, returning the minimum value per batch slice:
tensor = np.array([
[[12, 15], [18, 9]],
[[25, 30], [22, 28]]
])
batch_mins = tensor.min(axis=(1, 2))
print("Batch minimums (axis=(1, 2)):", batch_mins)
assert np.array_equal(batch_mins, np.array([9, 22]))Expected output
Batch minimums (axis=(1, 2)): [ 9 22]
In tabular operations, prices may be zero or unrecorded. We find the lowest valid nonzero price across regions using masked operations:
price_matrix = np.array([
[120.0, 0.0, 115.0],
[45.0, 40.0, 42.0],
[0.0, 210.0, 205.0]
])
valid_mask = price_matrix > 0.0
min_valid_prices = np.min(price_matrix, axis=1, where=valid_mask, initial=np.inf)
print("Lowest active price per product:", min_valid_prices)
assert np.array_equal(min_valid_prices, np.array([115.0, 40.0, 205.0]))Expected output
Lowest active price per product: [115. 40. 205.]
initial acts as a competitor, setting initial=0 on an array of positive numbers causes min() to return 0 instead of the true minimum element. Use initial=np.inf for positive numbers.axis=0 collapses downwards across rows (producing column minimums), while axis=1 collapses across columns (producing row minimums).keepdims=True when normalizing data causes shape mismatch errors when broadcasting back against original matrices.Given sensor temperature readings where missing values are flagged as -999, find the true minimum temperature recorded for each station:
readings = np.array([
[18, 22, -999, 19],
[-999, 14, 15, 12],
[25, 27, 26, 24]
])
# Target: Compute the minimum non-negative reading per row (station)
valid_readings = readings >= 0
station_min = readings.min(axis=1, where=valid_readings, initial=np.inf)
print("Clean station minimums:", station_min)
assert np.array_equal(station_min, np.array([18.0, 12.0, 24.0]))Expected output
Clean station minimums: [18. 12. 24.]
Test all minimum reduction operations, explore masked arrays, and run self-verifying test suites in our interactive Google Colab companion notebook:
Launch the notebook directly in Google Colab to run live code cells or inspect the source repository on GitHub:
View on GitHubContinue exploring related functions: max(), mean(), sum(), and axis reduction.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.