clip()
函数用于将数组中的值限制在指定的范围内。
示例
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
# clip values in array1 between 2 and 4 using clip()
clipped_array = np.clip(array1, 2, 4)
print(clipped_array)
# Output : [2 2 3 4 4]
clip() 语法
clip()
的语法是:
numpy.clip(array, array_min, array_max, out=None)
clip() 参数
clip()
函数可以接受以下参数:
array
- 输入数组array_min
- 最小值array_max
- 最大值out
(可选) - 允许我们指定一个用于存储结果的数组
注意:
- 如果 array 中的任何元素小于
array_min
,它将被设置为array_min
。 - 如果 array 中的任何元素大于
array_max
,它将被设置为array_max
。
clip() 返回值
clip()
方法返回裁剪后的数组,其中值被限制在指定范围内。
示例 1:裁剪数组
import numpy as np
array1 = np.array([-2, 0, 3, 7, 10])
# clip values in array1 between 0 and 5 using clip()
clipped_array = np.clip(array1, 0, 5)
print(clipped_array)
输出
[0 0 3 5 5]
在上面的示例中,我们有一个名为 array1 的数组,其值为 [-2, 0, 3, 7, 10]
。
我们使用 np.clip()
函数将 array1
中的值限制在 0 到 5 的范围内。
任何小于 0 的值将被裁剪为 0,任何大于 5 的值将被裁剪为 5。
示例 2:裁剪二维数组
import numpy as np
# create a 2-D array
array1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# use clip() to limit the values in the array to the range from 3 to 7
clipped_array = np.clip(array1, 3, 7)
print(clipped_array)
输出
[[3 3 3] [4 5 6] [7 7 7]]
示例 3:在 clip() 中使用 out 参数
import numpy as np
array1 = np.array([1, 2, 3, 4, 5])
# create array of zeros with the same shape as array1
out_array = np.zeros_like(array1)
# clip array1 and store the output in the out_array array
np.clip(array1, 2, 4, out=out_array)
print(out_array)
输出
[2 2 3 4 4]