In NumPy, array indexing is a powerful feature that allows you to access and manipulate elements within multi-dimensional arrays (also known as ndarrays). NumPy provides several ways to index arrays, including basic indexing, slicing, advanced indexing, and boolean indexing.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Accessing individual elements
print(arr[0]) # Output: 1
# Accessing slices
print(arr[1:4]) # Output: [2 3 4]
# 2D array
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]]
# Integer indexing
print(arr[[0, 2, 4]]) # Output: [1 3 5]
# Boolean indexing
mask = arr > 2
print(arr[mask]) # Output: [3 4 5]