NumPy Slicing and Indexing
The contents of an ndarray object can be accessed and modified through indexing or slicing, just like the slicing operations of lists in Python.
ndarray arrays can be indexed based on subscripts from 0 to n. Slicing objects can be created through the built-in slice function, and by setting the start, stop, and step parameters, a new array can be cut out from the original array.
Example
The output result is:
[2 4 6]
In the above example, we first created an ndarray object using the arange() function. Then, we set the start, stop, and step parameters to 2, 7, and 2 respectively.
We can also use colon-separated slice parametersstart:stop:stepto perform slicing operations:
Example
The output result is:
[2 4 6]
Colon:The explanation: if only one parameter is placed, such as[2], it will return the single element corresponding to that index. If it is[2:], it means all items from that index onward will be extracted. If two parameters are used, such as[2:7], then the items between the two indexes (excluding the stop index) will be extracted.
Example
The output result is:
5
Example
The output result is:
[2 3 4 5 6 7 8 9]
Example
The output result is:
[2 3 4]
Multidimensional arrays also apply the same indexing and extraction method above:
Example
The output result is:
[[1 2 3] [3 4 5] [4 5 6]] 从数组索引 a[1:] 处开始切割 [[3 4 5] [4 5 6]]
Slicing can also include an ellipsis…, to make the length of the selection tuple the same as the dimension of the array. If an ellipsis is used at the row position, it will return an ndarray containing the elements in the row.
Example
The output result is:
[2 4 5] [3 4 5] [[2 3] [4 5] [5 6]]Other Extensions