如何在 NumPy 中迭代列
NumPy 的名稱代表 Numerical Python。它有助於解決陣列上的數學運算。在 Python 中,我們有一些內建函式,例如 nditor()、T()、array()、shape[] 和 apply_along_axis(),它們將用於在 NumPy 中迭代列。
語法
以下語法在示例中使用 -
nditer()
NumPy 模組包含此用於迭代器物件的內建函式。
T()
此函式指的是列資料框中索引的轉置。
array()
這是 Python 中的一個內建函式,用於建立陣列。陣列透過收集相同資料型別的項來定義。
apply_along_axis()
apply_along_axis() 在輸入陣列的 1D 切片上執行給定函式,其中切片沿著我們選擇的軸進行。
Shape[]
這用於獲取名為 NumPy 的模組的維度。此外,還獲取 Pandas 模組的維度。
使用 nditer() 函式
該程式使用 for 迴圈,其中變數透過內建函式 nditer() 與 T() 迭代來在 NumPy 中迭代列。
示例
在以下示例中,我們將開始匯入名為 numpy 的模組並將物件引用作為 ny。然後使用內建函式 array() 與 ny 建立 4*3 矩陣陣列並將其儲存在變數 arr 中。接下來,使用 for 迴圈,其中變數 col 迭代 nditer(),該函式接受引數 - arr.T() 來轉置列的索引。最後,在 print 函式中使用變數 col 以獲取結果。
import numpy as ny # Create a sample 2D array arr = ny.array([[10, 20, 30], [40, 50, 60], [70, 80, 90], [110, 120, 130]]) print("Iteration of all the columns:") # Iterate over columns using nditer for col in ny.nditer(arr.T): print(col)
輸出
Iteration of all the columns: 10 20 30 40 50 60 70 80 90 110 120 130
使用陣列轉置
該程式使用矩陣的概念,它將矩陣按行轉置為列,並以此方式在 NumPy 中迭代列。
示例
在以下示例中,透過匯入模組開始程式,然後使用內建函式 array() 建立列表矩陣以儲存在變數 arr 中。現在使用 for 迴圈轉置輸入陣列矩陣,其中變數 col 在 arr.T 的幫助下迭代每一列。最後,我們使用變數 col 列印結果。
# import the module import numpy as np # create the list matrix arr = np.array([[1, 2, 3 ], [4, 5, 6], [7, 8, 9]] ) # Transpose array matrix for col in arr.T: print(col)
輸出
[1 4 7] [2 5 8] [3 6 9]
使用 apply_along_axis() 函式
該程式使用內建函式 apply_along_axis(),它將切片輸入陣列的給定函式以在 NumPy 中迭代每一列。
示例
在以下示例中,開始匯入模組,然後在變數 arr 中建立 2D 陣列表示。接下來,使用使用者定義的函式操作每一列,該函式接受名為 col 的引數,該引數透過內建函式 apply_along_axis() 接收值,它將列印列。最後,apply_along_matrix() 接受以下引數 -
p_column:這是第一個引數,作為命名函式定義傳遞給轉置陣列arr.T(第三個引數)的每一列。
0:第二個引數 0 指定應沿輸入陣列的第一軸(列)應用該函式。
arr.T:轉置陣列,這將有助於迭代列。
import numpy as np # 2D array representation arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # operate each column using the function def p_column(col): print(col) # Iterate the column np.apply_along_axis(p_column, 0, arr.T)
輸出
[1 2 3] [4 5 6] [7 8 9]
使用 While 迴圈
該程式使用 shape 方法獲取 NumPy 模組的維度,並使用 while 迴圈迭代輸入陣列的每一列。
示例
在以下示例中,開始匯入模組並建立輸入陣列以在變數 arr 中建立一個包含行和列的陣列列表。使用相同的變數,它將使用 Shape[] 獲取陣列的維度並將其儲存在變數 num_cols 中。然後將變數 col_index 初始化為 0,表示初始索引值。接下來,使用 while 迴圈使用 < 運算子設定條件。然後使用切片和增量生成結果。
import numpy as np # Create the 2D array arr = np.array([[1, 5, 9], [13, 14, 21], [25, 29, 33]]) # Get the number of columns num_cols = arr.shape[1] # Initialize the column index col_index = 0 # Using a while loop iterates over each column while col_index < num_cols: col = arr[:, col_index] print(col) col_index += 1
輸出
[ 1 13 25] [ 5 14 29] [ 9 21 33]
結論
我們討論瞭解決此問題陳述的各種方法。我們看到了 NumPy 的一些流行的迭代內建函式,即 nditer()、T() 和 shape[],它們有助於迭代列。NumPy 模組在以下操作中工作,例如線性代數、矩陣和傅立葉變換。