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


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

numpy.divide(arr1,arr2,out = None,where = True,cast ='same_kind',order ='K',dtype = None):
將第一個數組中的數組元素除以第二個元素中的元素(所有情況均逐個元素發生)。 arr1和arr2必須具有相同的形狀,並且arr2中的元素不能為零;否則會引發錯誤。

參數:

  • arr1 : [數組]輸入數組或對象,用作除數。
    arr2 : [數組]用作除數的輸入數組或對象。
    out : [ndarray,可選]尺寸與輸入數組相同的輸出數組,
    放在結果上。
    ** kwargs:允許您將關鍵字的可變參數長度傳遞給函數。
    當我們要處理函數中的命名參數時使用它。
    where : [數組,可選]真值表示要計算通用
    該位置的function(ufunc),False值表示離開
    僅在輸出中的值。

返回:

An array with arr1/arr2(element-wise) as elements of output array.


代碼1:arr1除以arr2元素

# Python program explaining 
# divide() function 
import numpy as np 
  
# input_array 
arr1 = [2, 27, 2, 21, 23] 
arr2 = [2, 3, 4, 5, 6] 
print ("arr1         : ", arr1) 
print ("arr2         : ", arr2) 
  
# output_array 
out = np.divide(arr1, arr2) 
print ("\nOutput array : \n", out)

輸出:

arr1         :  [2, 27, 2, 21, 23]
arr2         :  [2, 3, 4, 5, 6]

Output array : 
 [ 1.          9.          0.5         4.2         3.83333333]


代碼2:arr1的元素除以除數

# Python program explaining 
# divide() function 
import numpy as np 
  
# input_array 
arr1 = [2, 27, 2, 21, 23] 
divisor = 3
print ("arr1         : ", arr1) 
  
# output_array 
out = np.divide(arr1, divisor) 
print ("\nOutput array : \n", out)

輸出:

arr1         :  [2, 27, 2, 21, 23]

Output array : 
 [ 0.66666667  9.          0.66666667  7.          7.66666667]


代碼3:警告如果arr2的元素= 0

# Python program explaining 
# divide() function 
import numpy as np 
  
# input_array 
arr1 = [2, 27, 2, 21, 23] 
arr2 = [2, 3, 0, 5, 6] 
print ("arr1         : ", arr1) 
print ("arr2         : ", arr2) 
  
# output_array 
out = np.divide(arr1, arr2) 
print ("\nOutput array : ", out)

輸出:

arr1         :  [2, 27, 2, 21, 23]
arr2         :  [2, 3, 0, 5, 6]

Output array :  [ 1.          9.                 inf  4.2         3.83333333]
RuntimeWarning: divide by zero encountered in true_divide
  out = np.power(arr1, arr2)

參考文獻:
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.divide.html



相關用法


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