1D Array Indexing
Access elements in 1D arrays:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
# Single element
print(arr[0]) # 10 (first element)
print(arr[-1]) # 50 (last element)
# Slicing
print(arr[1:4]) # [20, 30, 40]
print(arr[:3]) # [10, 20, 30] (first 3)
print(arr[2:]) # [30, 40, 50] (from index 2)
2D Array Indexing
Access elements in 2D arrays (matrices):
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Single element
print(arr[0, 1]) # 2 (row 0, column 1)
# Entire row
print(arr[0]) # [1, 2, 3]
# Entire column
print(arr[:, 1]) # [2, 5, 8]
# Subarray
print(arr[0:2, 1:3]) # [[2, 3], [5, 6]]
Advanced Slicing
Use step size and advanced slicing:
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Step size
print(arr[::2]) # [0, 2, 4, 6, 8] (every 2nd)
# Reverse
print(arr[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Start, stop, step
print(arr[1:8:2]) # [1, 3, 5, 7]
Boolean Indexing
Filter arrays using conditions:
arr = np.array([1, 2, 3, 4, 5, 6])
# Get elements greater than 3
mask = arr > 3
print(arr[mask]) # [4, 5, 6]
# Direct filtering
print(arr[arr > 3]) # [4, 5, 6]
# Multiple conditions
print(arr[(arr > 2) & (arr < 6)]) # [3, 4, 5]
Fancy Indexing
Select elements using arrays of indices:
arr = np.array([10, 20, 30, 40, 50])
# Select specific indices
indices = [0, 2, 4]
print(arr[indices]) # [10, 30, 50]
# 2D fancy indexing
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
rows = [0, 2]
cols = [1, 2]
print(arr2d[rows, cols]) # [2, 9]
Modifying Arrays
Change array values:
arr = np.array([1, 2, 3, 4, 5])
# Modify single element
arr[0] = 10 # [10, 2, 3, 4, 5]
# Modify slice
arr[1:3] = [20, 30] # [10, 20, 30, 4, 5]
# Modify with condition
arr[arr > 3] = 0 # Set all > 3 to 0
Views vs Copies
Understand when operations create views or copies:
arr = np.array([1, 2, 3, 4, 5])
# Slicing creates view (shares memory)
view = arr[1:4]
view[0] = 99
print(arr) # [1, 99, 3, 4, 5] (original changed!)
# Explicit copy
copy = arr[1:4].copy()
copy[0] = 100
print(arr) # [1, 99, 3, 4, 5] (original unchanged)
Best Practices
- Use boolean indexing: Fast and readable
- Be aware of views: Slicing creates views, not copies
- Use copy() when needed: To avoid modifying original
- Prefer vectorized operations: Faster than loops
Next Steps
Learn about creating arrays or array operations.