當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python numpy.clip()用法及代碼示例

numpy.clip()函數用於剪輯(限製)數組中的值。

給定一個間隔,該間隔以外的值將被裁剪到間隔邊。例如,如果指定間隔[0,1],則小於0的值將變為0,而大於1的值將變為1。

用法: numpy.clip(a, a_min, a_max, out=None)

參數:
a:包含要裁剪的元素的數組。
a_min:最小值。
->如果為“無”,則不會在較低間隔的邊執行剪切。 a_min和a_max中最多一個可以為None。
a_max :最大值。
->如果為“無”,則不會在間隔的上限邊執行剪切。 a_min和a_max中最多一個可以為None。
->如果a_min或a_max是數組,則將廣播這三個數組以匹配其形狀。
out :結果將放置在此數組中。它可能是就地剪切的輸入數組。輸出必須具有正確的形狀以容納輸出。其類型被保留。

Return :clipped_array

代碼1:

# Python3 code demonstrate clip() function 
  
# importing the numpy 
import numpy as np 
  
in_array = [1, 2, 3, 4, 5, 6, 7, 8 ] 
print ("Input array:", in_array) 
  
out_array = np.clip(in_array, a_min = 2, a_max = 6) 
print ("Output array:", out_array)

輸出:

Input array: [1, 2, 3, 4, 5, 6, 7, 8]
Output array: [2 2 3 4 5 6 6 6]


代碼2:

# Python3 code demonstrate clip() function 
  
# importing the numpy 
import numpy as np 
  
in_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
print ("Input array:", in_array) 
  
out_array = np.clip(in_array, a_min =[3, 4, 1, 1, 1, 4, 4, 4, 4, 4], 
                                                         a_max = 9) 
print ("Output array:", out_array)

輸出:

Input array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output array: [3 4 3 4 5 6 7 8 9 9]


相關用法


注:本文由純淨天空篩選整理自jana_sayantan大神的英文原創作品 numpy.clip() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。