numpy.clip() function can limit a numpy array in [min, max]. In this tutorial, we will use some examples to show you how to use it.
numpy.clip()
It is defined as:
ndarray.clip(min=None, max=None, out=None, **kwargs)
Here is a simple example.
import numpy as np x = np.random.random([3, 4]) print(x) min = 0.2 max = 0.6 y = np.clip(x, min, max) print(y)
As to x, it is:
[[0.85560928 0.37702509 0.44289704 0.98446548] [0.1586248 0.3948192 0.78732616 0.9485501 ] [0.79909917 0.36843706 0.71295046 0.15466975]]
After we have used np.clip(x, 0.2, 0.6), y will be:
[[0.6 0.37702509 0.44289704 0.6 ] [0.2 0.3948192 0.6 0.6 ] [0.6 0.36843706 0.6 0.2 ]]
numpy.clip() and array.clip(min, max)
We should notice: numpy.clip = array.clip()
For example:
min = 0.2 max = 0.6 y = np.clip(x, min, max) print(y) z = x.clip(min, max) print(z)
Run this code, we will find y and z are:
[[0.2 0.6 0.6 0.2 ] [0.6 0.56058524 0.6 0.3832909 ] [0.31922628 0.36651994 0.40016733 0.23430817]] [[0.2 0.6 0.6 0.2 ] [0.6 0.56058524 0.6 0.3832909 ] [0.31922628 0.36651994 0.40016733 0.23430817]]