Python–遍历NumPy中的列
Numpy(“数值Python ”的缩写)是⼀个⽤于以快速有效的⽅式执⾏⼤规模数学运算的库。本⽂旨在教育您关于可以在2D NumPy数组中的列上进⾏迭代的⽅法。由于⼀维数组仅由线性元素组成,因此不存在对其中的⾏和列的明确定义。因此,为了执⾏此类操作,我们需要⼀个数组,其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 = shape(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]
python 定义数组说明:
在上⾯的代码中,我们⾸先使⽤创建⼀个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该数组依次切换带有列的⾏和带有⾏的列。然后,我们遍历此转置数组的每⼀⾏并打印⾏值