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.
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:
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)
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[1:3])
Output
[25 30]
Example: Slicing from index 2 to 5 (5 is excluded)
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[2:5])
Output
[30 35 40]
Example: Slicing from index 5 to last
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[5:])
Output
[45 50 55 60, 65]
Example: Slicing from beginning to index 5 (5 is excluded)
import numpy as np n = np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 65]) print(n[:5])
Output
[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
arr[start:end:step}
Example
# Slice 1D arrays with STEP in NumPy import numpy as np n = np.array([100, 120, 130, 145, 160, 175, 187, 199, 210, 222, 240]) print(n[1:10:2]) print(n[1:10:3]) print(n[0:10:2]) print(n[0:10:3])
Output
[120 145 175 199 222] [120 160 199] [100 130 160 187 210] [100 145 187 222]
Slicing 2D arrays
The following are the examples of slicing Two-Dimensional arrays
Example: Slicing from index 2 to 5 (excluding 5)
# Slice 2D arrays in NumPy
# Slice from index 2 to 5 (excluding 5)
import numpy as np
n = np.array([[10, 30, 50, 79, 90, 95],
[4, 8, 12, 20, 25, 30],
[15, 28, 32, 40, 55, 70]])
print(n[0,2:5])
print(n[1,2:5])
print(n[2,2:5])
Output
[50 79 90] [12 20 25] [32 40 55]
Example: Slicing for both the dimensions
# Slice 2D arrays in NumPy
# Slice for both the dimension
import numpy as np
n = np.array([[10, 30, 50, 79, 90, 95],
[4, 8, 12, 20, 25, 30],
[15, 28, 32, 40, 55, 70]])
print(n[0:3, 2:5])
print(n[1:, 2:5])
print(n[0:, 2:5])
Output
[[50 79 90] [12 20 25] [32 40 55]] [[12 20 25] [32 40 55]] [[50 79 90] [12 20 25] [32 40 55]]
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