0
0
NumPydata~5 mins

np.clip() for bounding values in NumPy

Choose your learning style9 modes available
Introduction

We use np.clip() to keep numbers within a set range. It stops values from going too low or too high.

When you want to limit temperatures to a safe range in a weather dataset.
When you need to keep scores between 0 and 100 in a grading system.
When you want to avoid extreme values in sensor data that might be errors.
When normalizing data but want to keep values within a fixed boundary.
Syntax
NumPy
numpy.clip(a, a_min, a_max, out=None, **kwargs)

a is the input array or number.

a_min and a_max set the lower and upper bounds.

Examples
This clips values below 3 to 3, and above 12 to 12.
NumPy
np.clip([1, 5, 10, 15], 3, 12)
Clips a single number 7 to max 5, so result is 5.
NumPy
np.clip(7, 0, 5)
Clips values below 0 to 0; no upper limit.
NumPy
np.clip([-2, 0, 2], 0, None)
Sample Program

This program shows how values below 0 become 0, and above 10 become 10.

NumPy
import numpy as np

# Original data with some values out of range
data = np.array([2, 8, 15, -3, 7])

# Clip values to be between 0 and 10
clipped_data = np.clip(data, 0, 10)

print('Original data:', data)
print('Clipped data:', clipped_data)
OutputSuccess
Important Notes

If a_min or a_max is None, that bound is ignored.

Works with arrays or single numbers.

Useful to avoid unexpected extreme values in data.

Summary

np.clip() keeps values inside a range by setting limits.

It works on arrays or single numbers easily.

Great for cleaning or controlling data values.