使用 NumPy 將每一行除以向量元素
我們可以將 NumPy 陣列的每一行除以向量元素。向量元素可以是單個元素、多個元素或陣列。在將陣列的行除以向量以生成所需功能後,我們使用**除法 (/) 運算子**。行的除法可以是 1 維、2 維或多個數組。
有不同的方法可以執行將每一行除以向量元素的操作。讓我們詳細瞭解每種方法。
使用廣播
使用 divide() 函式
使用 apply_along_axis() 函式
使用廣播
廣播是 NumPy 庫中提供的一種方法,它允許對不同形狀的陣列執行數學運算。如果其中一個數組小於另一個數組,則廣播會自動將較小陣列的形狀與較大陣列的形狀匹配,並逐元素應用數學運算。
語法
以下是使用廣播的語法:
array / vector[:, np.newaxis]
示例
讓我們看一個使用 NumPy 庫的廣播方法將每一行除以向量元素的示例。
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("The array:",arr) vec = np.array([1, 2, 3]) print("The vector to divide the row:",vec) output = arr / vec[:, np.newaxis] print("The output of the divison of rows by vector using broadcast:",output)
輸出
The array: [[1 2 3] [4 5 6] [7 8 9]] The vector to divide the row: [1 2 3] The output of the divison of rows by vector using broadcast: [[1. 2. 3. ] [2. 2.5 3. ] [2.33333333 2.66666667 3. ]]
使用 divide() 函式
NumPy 庫提供了一個名為 divide() 的函式,用於將定義的陣列的行除以向量元素。此函式將陣列和向量作為輸入引數。
語法
以下是使用 divide() 函式的語法。
np.divide(array, vector[:, np.newaxis])
示例
在以下示例中,我們使用 divide() 函式將陣列的行除以向量元素。
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("The array:",arr) vec = np.array([1, 2, 3]) print("The vector to divide the row:",vec) output = np.divide(arr, vec[:, np.newaxis]) print("The output of the divison of rows by vector using divide function:",output)
輸出
The array: [[1 2 3] [4 5 6] [7 8 9]] The vector to divide the row: [1 2 3] The output of the divison of rows by vector using divide function: [[1. 2. 3. ] [2. 2.5 3. ] [2.33333333 2.66666667 3. ]]
使用 apply_along_axis() 函式
NumPy 中的 apply_along_axis() 函式允許使用者沿 NumPy 陣列的特定軸應用函式。此方法可用於執行各種操作,例如將 2D 陣列的行除以向量。
語法
以下是使用 apply_along_axis() 函式將陣列的行除以向量元素的語法。
np.apply_along_axis(row/vector, 1, array, vector)
示例
在以下示例中,我們使用 apply_along_axis() 函式將 2D 陣列的行除以定義的 2D 陣列向量。
import numpy as np arr = np.array([[1, 2, 3,1], [4, 5, 6,4], [7, 8, 9,7],[10,11,1,2]]) print("The array:",arr) vec = np.array([1, 2, 3,4]) print("The vector to divide the row:",vec) def divide_row(row, vec): return row / vec output = np.apply_along_axis(divide_row, 1, arr, vec) print("The output of the divison of rows by vector using divide function:",output)
輸出
The array: [[ 1 2 3 1] [ 4 5 6 4] [ 7 8 9 7] [10 11 1 2]] The vector to divide the row: [1 2 3 4] The output of the divison of rows by vector using divide function: [[ 1. 1. 1. 0.25 ] [ 4. 2.5 2. 1. ] [ 7. 4. 3. 1.75 ] [10. 5.5 0.33333333 0.5 ]]
廣告