Indexing and Slicing
Accessing and modifying parts of an array is done through indexing and slicing. NumPy extends Python’s slicing syntax to multiple dimensions, which is very useful for image patches or extracting subsets of data.
1D Indexing and Slicing
Similar to Python lists.
arr = np.array([10,20,30,40,50])
print(arr[0]) # 10
print(arr[1:4]) # [20,30,40]
arr[2] = 99 # modify
print(arr) # [10,20,99,40,50]2D Indexing (Rows and Columns)
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix[0,1]) # 2 (row0, col1)
print(matrix[1]) # [4,5,6] (row1)
print(matrix[:,1]) # [2,5,8] (all rows, column1)
print(matrix[0:2, 1:3]) # [[2,3],[5,6]]Boolean Indexing (Filtering)
Select elements based on a condition.
data = np.array([1,5,8,12,3])
mask = data > 5
print(mask) # [False,False,True,True,False]
print(data[mask]) # [8,12]Fancy Indexing (Using Integer Lists)
Select arbitrary positions.
arr = np.array([10,20,30,40,50])
indices = [0,2,4]
print(arr[indices]) # [10,30,50]Why This Matters for AI
You’ll often need to extract specific rows/columns from datasets, filter data based on labels, or extract image patches. NumPy indexing makes these operations fast and concise.
Two Minute Drill
- Use
array[row, col]for 2D indexing. - Slicing:
start:stop:stepfor each dimension. - Boolean indexing:
array[condition]. - Fancy indexing:
array[list_of_indices].
Need more clarification?
Drop us an email at career@quipoinfotech.com
