NumPy: clip() to limit array values to min and max

Modified: | Tags: Python, NumPy

In NumPy, use the np.clip() function or the clip() method of ndarray to limit array values to a specified range, replacing out-of-range values with the specified minimum or maximum value.

The NumPy version used in this article is as follows. Note that functionality may vary between versions.

import numpy as np

print(np.__version__)
# 1.26.1

How to use the np.clip() function

In np.clip(), the first argument a is the array (ndarray) to be processed, the second argument a_min is the minimum value, and the third argument a_max is the maximum value.

a = np.arange(10)
print(a)
# [0 1 2 3 4 5 6 7 8 9]

print(np.clip(a, 2, 7))
# [2 2 2 3 4 5 6 7 7 7]

To specify only the minimum or maximum value, use None for the other value. Neither can be omitted.

print(np.clip(a, None, 7))
# [0 1 2 3 4 5 6 7 7 7]

print(np.clip(a, 2, None))
# [2 2 2 3 4 5 6 7 8 9]

# print(np.clip(a, 2))
# TypeError: clip() missing 1 required positional argument: 'a_max'

Even if a_min is greater than a_max, it will not result in an error, and all values will become a_max.

print(np.clip(a, 7, 2))
# [2 2 2 2 2 2 2 2 2 2]

It returns a clipped ndarray, leaving the original ndarray unchanged.

a_clip = np.clip(a, 2, 7)
print(a_clip)
# [2 2 2 3 4 5 6 7 7 7]

print(a)
# [0 1 2 3 4 5 6 7 8 9]

For the first argument a, not only an ndarray but also other array-like objects, such as Python built-in lists, can be specified. The returned value is always an ndarray.

l = list(range(10))
print(l)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(np.clip(l, 2, 7))
# [2 2 2 3 4 5 6 7 7 7]

print(type(np.clip(l, 2, 7)))
# <class 'numpy.ndarray'>

How to use the clip() method of ndarray

In the clip() method of ndarray, the first argument min is for the minimum value and the second argument max for the maximum value.

a = np.arange(10)
print(a)
# [0 1 2 3 4 5 6 7 8 9]

print(a.clip(2, 7))
# [2 2 2 3 4 5 6 7 7 7]

print(a.clip(None, 7))
# [0 1 2 3 4 5 6 7 7 7]

print(a.clip(2, None))
# [2 2 2 3 4 5 6 7 8 9]

Unlike np.clip(), default values of None are set for the first argument min and the second argument max, so they can be omitted.

print(a.clip(2))
# [2 2 2 3 4 5 6 7 8 9]

print(a.clip(min=2))
# [2 2 2 3 4 5 6 7 8 9]

print(a.clip(max=7))
# [0 1 2 3 4 5 6 7 7 7]

Similar to np.clip(), if min is greater than max, all values will become max.

print(a.clip(7, 2))
# [2 2 2 2 2 2 2 2 2 2]

It returns a clipped ndarray, leaving the original ndarray unchanged.

a_clip = a.clip(2, 7)
print(a_clip)
# [2 2 2 3 4 5 6 7 7 7]

print(a)
# [0 1 2 3 4 5 6 7 8 9]

Related Categories

Related Articles