NumPy slicing is a powerful feature that allows you to extract sub-arrays or specific elements from multi-dimensional arrays (ndarrays). Slicing in NumPy follows a similar syntax to slicing in Python lists, but it extends to multiple dimensions.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Slicing the array
print(arr[1:4]) # Output: [2 3 4]
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Slicing rows and columns
print(arr_2d[:2, 1:]) # Output: [[2 3]
# [5 6]]
# Negative slicing
print(arr[-3:]) # Output: [3 4 5]
# Strided slicing
print(arr[::2]) # Output: [1 3 5]