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数组依次切换带有列的行和带有行的列。然后,我们遍历此转置数组的每一行并打印行值

posted @ 2020-10-25 20:11  DaisyLinux  阅读(8911)  评论(0编辑  收藏  举报