Array indexing and slicing are essential operations for accessing and manipulating elements within NumPy arrays. These techniques provide flexibility in extracting specific subsets of data or modifying array values.
Basic Indexing
Single Element Access:
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Access the first element
element = arr[0]
Multidimensional Indexing:
Python
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
# Access the element at the second row, first column
element = arr2d[1, 0]
Slicing
Extracting Subarrays:
Python
# Extract elements from the second to fourth position
slice = arr[1:4]
# Extract the first two rows and columns
slice2d = arr2d[:2, :2]
Negative Indexing:
Python
# Access the last element
last_element = arr[-1]
# Extract the last two elements
last_two = arr[-2:]
Step Size:
Python
# Extract every other element
every_other = arr[::2]
Advanced Indexing
Boolean Indexing:
Python
mask = arr > 3
# Extract elements where the mask is True
result = arr[mask]
Fancy Indexing:
Python
indices = np.array([0, 2, 4])
# Extract elements at the specified indices
result = arr[indices]
Modifying Array Elements
Assignment:
Python
arr[0] = 10
arr2d[1, 2] = 20
In-place Operations:
Python
arr += 1 # Increment all elements by 1
By mastering array indexing and slicing, you can efficiently extract, modify, and manipulate elements within NumPy arrays, enabling a wide range of data analysis and manipulation tasks.