29 Mar NumPy – Array Slicing
Slicing the array in a range from start to end is what we call Array Slicing. Slice (range) is passed in place of index i.e.
1 2 3 |
n[1:3] |
The above will slice two elements from index 1 to index 3 because it includes the start index, but excludes the end index.
The following is the syntax to slice NumPy arrays:
1 2 3 |
arr[start:end] |
Here, the start is the beginning index (include), and the end is the last index (excluded)
Slicing Examples
The following Array Slicing examples we will run:
- Slicing from index 1 to 3 (3 is excluded)
- Slicing from index 2 to 5 (5 is excluded)
- Slicing from index 5 to last
- Slicing from the beginning to index 5 (5 is excluded)
Example: Slicing from index 1 to 3 (3 is excluded)
1 2 3 4 5 6 |
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[1:3]) |
Output
1 2 3 |
[25 30] |
Example: Slicing from index 2 to 5 (5 is excluded)
1 2 3 4 5 6 |
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[2:5]) |
Output
1 2 3 |
[30 35 40] |
Example: Slicing from index 5 to last
1 2 3 4 5 6 |
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[5:]) |
Output
1 2 3 |
[45 50 55 60, 65] |
Example: Slicing from beginning to index 5 (5 is excluded)
1 2 3 4 5 6 |
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[:5]) |
Output
1 2 3 |
[20 25 30 35 40] |
Slice 1D arrays with STEP
We can also include steps while slicing. Step means a jump of elements. If the step is 2, that means 2 jumps for the next element.
Syntax
1 2 3 |
arr[start:end:step} |
Example
1 2 3 4 5 6 |
import numpy as np n = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60]) print(n[1:10:2]) |
Output
1 2 3 |
[10 20 30 40 50] |
Slicing 2D arrays with STEP
The following are the examples of slicing Two-Dimensional arrays with steps:
Example: Slicing from index 2 to 5 (excluding 5)
1 2 3 4 5 6 |
import numpy as np n = np.array([[10,30,50,70,90,95],[4,8,12,14,16,18]]) print(n[0,2:5]) |
Output
1 2 3 |
[50 70 90] |
Example: Slicing for both the dimensions with step
1 2 3 4 5 6 |
import numpy as np n = np.array([[10, 30, 50, 70, 90, 95], [4, 8, 12, 14, 16, 18]]) print(n[0:2, 2:5]) |
Output
1 2 3 4 |
[[50 70 90] [12 14 16]] |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments