如何在Python中检索数组的整个行或列
数组是一组类似的元素组合在一起形成的单一实体,也就是说,它基本上是整数、浮点数、字符等的集合。行和列的索引从0开始。
一维数组
一维数组形成了一个类似数据类型归属元素的矢量。它包含单行元素,每个元素都落入不同的列。一维数组的尺寸是[1 x c],其中c是列的数量。可以使用其相应的索引访问数组中的任何一列。由于这个数组包含一个单行,所以打印该数组就相当于打印第一行。
array - retrieves the column at cth index (c+1 row)
下面的Python代码说明了在一个一维数组中检索整列的过程。
# importing the required package
import numpy as np
# creating a numpy character array
arr1 = np.array(["Ram", "Shyam" , "Sita"])
print("First row - ")
print(arr1)
# printing first column referred by first index
print ("First Column")
print (arr1[0])
# computing length of array
length = len(arr1)
print("Last Column")
print (arr1[length-1])
输出:
Original Array -
['Ram' 'Shyam' 'Sita']
First Column
Ram
Last Column
Sita
也可以通过指定开始和最后的索引从一维数组中检索出一个列的范围。如果我们不指定最后的索引,那么数组将被打印到数组的末端。
array[start : end] – 检索从start index到end-1 index的数组列。
下面的python代码用于检索一个一维数组中的列的范围。
# importing the required package
import numpy as np
# creating a numpy integer array
arr1 = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print("First two columns")
print(arr1[0:2])
# printing columns in a range
print("Columns in a range")
print(arr1[4:7])
# computing length of array
length = len(arr1)
print("Last 3 Columns")
print(arr1[length-3:length])
print("Array till the end")
print(arr1[3:])
输出:
First two columns
[1 2]
Columns in a range
[5 6 7]
Last 3 Columns
[6 7 8]
Array till the end
[4 5 6 7 8]
多维数组
多维阵列是一连串的行堆叠在一起,形成一个矩阵。矩阵包含类似的元素,属于整数、字符和双数。它的尺寸是[r x c],其中r是行的数量,c是列的数量。
matrix [r] - prints row at r index
matrix[ : , c] - prints column at c index
下面的Python代码说明了检索一整行或一整列的过程。
# importing the required package
import numpy as np
# creating a numpy integer array
mat1 = np.array([[1, 2, 3], [4, 5, 6]])
print("Original matrix ")
print(mat1)
print("Row at 0th index")
print(mat1[0])
# 1st columns
print("Column at 1st index")
print(mat1[:, 1])
# computing length of array
print("Column at 2nd index")
print(mat1[:, 2])
输出:
Original matrix
[[1 2 3]
[4 5 6]]
Row at 0th index
[1 2 3]
Column at 1st index
[2 5]
Column at 2nd index
[3 6]
也可以在矩阵中打印属于某个范围的行或列。我们指定矩阵的行和列的开始和结束索引。如果我们把结束索引留空,它就会打印出直到矩阵长度的列或行。
# importing the required package
import numpy as np
# creating a numpy integer array
mat1 = np.array([[1, 2, 3, 4], [4, 5, 6, 8], [7, 6, 8, 9]])
print("Original matrix ")
print(mat1)
print("Row from 1st to 2nd index")
print(mat1[1:3])
# 1st columns
print("Last three columns")
# prints all the columns till the end
print(mat1[:, 1:])
# printing a subset of matrix
print("Matrix subset")
# row index 1 and 2 inclusive and col_index 2 and 3 inclusive
print(mat1[1:3, 2:4])
输出:
Original matrix
[[1 2 3 4]
[4 5 6 8]
[7 6 8 9]]
Row from 1st to 2nd index
[[4 5 6 8]
[7 6 8 9]]
Last three columns
[[2 3 4]
[5 6 8]
[6 8 9]]
Matrix subset
[[6 8]
[8 9]]