Python –遍歷NumPy中的列


 
 

Numpy(“數值Python ”的縮寫)是一個用於以快速有效的方式執行大規模數學運算的庫。本文旨在教育您關於可以在2DNumPy數組中的列上進行迭代的方法由於一維數組僅由線性元素組成,因此不存在對其中的行和列的明確定義。因此,為了執行此類操作,我們需要一個數組,其len(ary.shape) > 1 

NumPy在您的python環境中安裝,請在操作系統的命令處理器(CMD,Bash等)中鍵入以下代碼

我們將研究在數組/矩陣的列上進行迭代的幾種方法:

方法1: 

代碼:對數組使用原始2D切片操作以獲取所需的列/列

import numpy as np 

# Creating a sample numpy array (in 1D) 
ary = np.arange(1, 25, 1) 

# Converting the 1 Dimensional array to a 2D array 
# (to allow explicitly column and row operations) 
ary = ary.reshape(5, 5) 

# Displaying the Matrix (use print(ary) in IDE) 
print(ary) 

# This for loop will iterate over all columns of the array one at a time 
for col in range(ary.shape[1]): 
    print(ary[:, col]) 

 

輸出:
[[0,1,2,3,4],
 [5,6,7,8,9],
 [10,11,12,13,13,14],
 [15、16、17、18、19],
 [20、21、22、23、24]])


[0 5 10 15 20]
[1 6 11 16 21]
[2 7 12 17 22]
[3 8 13 18 23]
[4 9 14 19 24]

說明:

在上面的代碼中,我們首先使用創建一個25個元素(0-24)的線性數組np.arange(25)然后,使用np.reshape()從線性數組中創建2D數組,將其重塑(將1D轉換為2D)然后我們輸出轉換后的數組。現在,我們使用了一個for循環,該循環將迭代x次(其中x是數組中的列數),並range()與參數一起使用ary.shape[1](其中shape[1]= 2D對稱數組中的列數)。在每次迭代中,我們從數組中輸出一列,使用ary[:, col]表示給定列的所有元素number = col

方法2:
在此方法中,我們將轉置數組以將每個列元素都視為行元素(而后者等效於列迭代)。

# libraries 
import numpy as np 

# Creating an 2D array of 25 elements 
ary = np.array([[ 0, 1, 2, 3, 4], 
                [ 5, 6, 7, 8, 9], 
                [10, 11, 12, 13, 14], 
                [15, 16, 17, 18, 19], 
                [20, 21, 22, 23, 24]]) 


# This loop will iterate through each row of the transposed 
# array (equivalent of iterating through each column) 
for col in ary.T: 
    print(col) 

輸出:


[0 5 10 15 20]
[1 6 11 16 21]
[2 7 12 17 22]
[3 8 13 18 23]
[4 9 14 19 24]

說明:
首先,我們使用創建了一個2D數組(與前面的示例相同),np.array()並使用25個值對其進行了初始化。然后,我們轉置數組,使用ary.T數組依次切換帶有列的行和帶有行的列。然后,我們遍歷此轉置數組的每一行並打印行值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM