NumPy — Array Indexing
Integer indexing
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
indices = [0, 2, 4]
print(arr[indices]) # [10, 30, 50]
2D integer indexing
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
rows = [0, 1, 2]
cols = [0, 1, 2]
print(arr[rows, cols]) # [1, 5, 9]
Boolean indexing
arr = np.array([1, 2, 3, 4, 5])
mask = arr > 3
print(arr[mask]) # [4, 5]
Multiple conditions
arr = np.array([1, 2, 3, 4, 5])
mask = (arr > 2) & (arr < 5)
print(arr[mask]) # [3, 4]
np.where
arr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 3, 1, 0)
print(result) # [0, 0, 0, 1, 1]
argwhere
arr = np.array([1, 2, 3, 4, 5])
indices = np.argwhere(arr > 3)
print(indices) # [[3], [4]]
Mini Practice
- Use integer indexing
- Apply boolean masks
- Combine conditions
- Use np.where and argwhere
Up Next
Continue with Structured Arrays - Custom dtypes.
Related Topics
Frequently Asked Questions about Array Indexing
What is Array Indexing in NumPy?
Array Indexing is a fundamental concept in NumPy. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Array Indexing?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Array Indexing.
Why is Array Indexing important in NumPy?
Array Indexing is essential for NumPy development. Understanding this concept will help you write better code and solve real-world problems more effectively.