LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Python Data Science NumPy Array Slicing
Slicing Arrays: slicing in python means taking elements from one given index to another given index.
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0.
If we don't pass end its considered length of array in that dimension.
If we don't pass step its considered 1.
Example 1: Slice elements from index 1 to index 5 from the following array.
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
print(arr[1:5])
the output will be
[12 13 14 15]
Note: The result includes the start index, but excludes the end index.
Example 2: Slice elements from index 4 to the end of the array.
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
print(arr[4:])
the output will be
[15 16 17]
Example 3: Slice elements from the beginning to index 4 (not included).
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
print(arr[:4])
the output will be
[11 12 13 14]
Negative Slicing
In negative slicing the minus operator is used to refer to an index from the end.
Example 4: Slice from the index 3 from the end to index 1 from the end.
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
print(arr[-3:-1])
the output will be
[15 16]
STEP: Use the step value to determine the step of the slicing.
Example 5: Return every other element from index 1 to index 5.
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
print(arr[1:5:2])
the output will be
[12 14]
Example 6: Return every other element from the entire array.
Code
import numpy as np
arr = np.array([11, 12, 13, 14, 15, 16, 17])
print(arr[::2])
the output will be
[11 13 15 17]
Slicing 2-D Arrays
Example 7: From the second element, slice elements from index 1 to index 4 (not included).
Code
import numpy as np
arr = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print(arr[1, 1:4])
the output will be
[17 18 19]
Note: Remember that second element has index 1.
Example 8: From both elements, return index 2.
Code
import numpy as np
arr = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print(arr[0:2, 2])
the output will be
[13 18]
Example 9: From both elements, slice index 1 to index 4 (not included), this will return a 2-D array.
Code
import numpy as np
arr = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print(arr[0:2, 1:4])
the output will be
[[12 13 14] [17 18 19]]