Ndarry 切片
正如之前提到的,我们除了能够一次访问一个元素之外,NumPy 还提供了访问 ndarray 子集的方式,称之为切片。切片方式是在方括号里用冒号 :
分隔起始和结束索引。通常,你将遇到三种类型的切片:
1. ndarray[start:end]
2. ndarray[start:]
3. ndarray[:end]
第一种方法用于选择在 start
和 end
索引之间的元素。第二种方法用于选择从 start
索引开始直到最后一个索引的所有元素。第三种方法用于选择从第一个索引开始直到 end
索引的所有元素。请注意,在第一种方法和第三种方法中,结束索引不包括在内。此外注意,因为 ndarray 可以是多维数组,在进行切片时,通常需要为数组的每个维度指定一个切片。 ==注:start是从start开始,包括start,end是截止到end,不包括end,因此end数多一== 现在我们将查看一些示例,了解如何使用上述方法从秩为 2 的 ndarray 中选择不同的子集。
# We create a 4 x 5 ndarray that contains integers from 0 to 19
X = np.arange(20).reshape(4, 5)
# We print X
print()
print('X = \n', X)
print()
# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 5th columns
Z = X[1:4,2:5]
# We print Z
print('Z = \n', Z)
# We can select the same elements as above using method 2
W = X[1:,2:5]
# We print W
print()
print('W = \n', W)
# We select all the elements that are in the 1st through 3rd rows and in the 3rd to 5th columns
Y = X[:3,2:5]
# We print Y
print()
print('Y = \n', Y)
# We select all the elements in the 3rd row
v = X[2,:]
# We print v
print()
print('v = ', v)
# We select all the elements in the 3rd column
q = X[:,2]
# We print q
print()
print('q = ', q)
# We select all the elements in the 3rd column but return a rank 2 ndarray
R = X[:,2:3]
# We print R
print()
print('R = \n', R)
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Z =
[[ 7 8 9]
[12 13 14]
[17 18 19]]
W =
[[ 7 8 9]
[12 13 14]
[17 18 19]]
Y =
[[ 2 3 4]
[ 7 8 9]
[12 13 14]]
v = [10 11 12 13 1