Numpy Indexing And Slicing
# NumPy Slicing and Indexing
The content of ndarray objects 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 using the built-in `slice` function, setting the `start`, `stop`, and `step` parameters to cut out a new array from the original array.
## Example
import numpy as np a = np.arange(10)s = slice(2,7,2)# From index 2 to index 7, with a step of 2 print(a)
The output result is:
In the above example, we first create 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 perform slicing operations by separating the slicing parameters with a colon **start:stop:step**:
## Example
import numpy as np a = np.arange(10)b = a[2:7:2]# From index 2 to index 7, with a step of 2 print(b)
The output result is:
Explanation of the colon `:`: If only one parameter is placed, like ****, it will return the single element corresponding to that index. If it is **[2:]**, it means all items from that index onwards will be extracted. If two parameters are used, like **[2:7]**, then the items between the two indices (excluding the stop index) will be extracted.
## Example
import numpy as np a = np.arange(10)# b = aprint(b)
The output result is:
5
## Example
import numpy as np a = np.arange(10)print(a[2:])
The output result is:
## Example
import numpy as np a = np.arange(10)# print(a[2:5])
The output result is:
The above indexing and extraction methods also apply to multi-dimensional arrays:
## Example
import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]])print(a)# Slice from a certain index print('Slice from array index a[1:]')print(a[1:])
The output result is:
[ ]Slice from array index a[1:][ ]
Slicing can also include the ellipsis `β¦` to make the length of the selection tuple equal to the number of dimensions in the array. If the ellipsis is used in the row position, it will return an ndarray containing the elements in the row.
## Example
import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]])print(a[...,1])# Elements of the 2nd column print(a[1,...])# Elements of the 2nd row print(a[...,1:])# Elements of the 2nd column and all remaining elements
The output result is:
[ ]
YouTip