note.nkmk.me

NumPy: Limit ndarray values to min and max with clip()

Posted: 2021-01-24 / Tags: Python, NumPy

To limit the values of the NumPy array ndarray to an arbitrary range, use np.clip() or clip() method of ndarray.

By specifying the minimum and maximum values in the argument, the out-of-range values are replaced with those values.

This is useful when you want to limit the values to a range such as 0.0 ~ 1.0 or 0 ~ 255.

This article describes the following contents.

  • How to use np.clip()
  • How to use clip() method of ndarray
Sponsored Link

How to use np.clip()

Specify the target array ndarray in the first argument a, the minimum value in the second argument a_min, and the maximum value in the third argument a_max.

import numpy as np

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]

Use None if you want to specify only one of the minimum and maximum values. It cannot 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'

The clipped ndarray is returned and the original ndarray remains 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]

How to use clip() method of ndarray

The clip() method of ndarray is almost the same.

Specify the minimum value in the first argument min and the maximum value in the second argument max.

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(), min and max can be omitted because None is set as the default value for min and max.

Note that the argument names are slightly different from np.clip(), so be careful when specifying them as keyword arguments.

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]

As with np.clip(), the clipped ndarray is returned and the original ndarray remains 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]
Sponsored Link
Share

Related Categories

Related Articles