← Back to Python

All Topics

Advertisement

Learn/Python/Data Science

NumPy Array Indexing

Topic: NumPy

Advertisement

Introduction

NumPy offers flexible and powerful indexing capabilities for accessing array elements.

Basic Indexing

arr = np.array([10, 20, 30, 40, 50])

print(arr[0])     # First element: 10
print(arr[-1])    # Last element: 50
print(arr[1:4])    # Elements 1 to 3: [20, 30, 40]

2D Array Indexing

matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

# Row access
print(matrix[0])       # First row
print(matrix[0, :])   # First row

# Column access
print(matrix[:, 1])   # Second column

# Element access
print(matrix[1, 2])   # Row 1, Col 2: 6

Fancy Indexing

arr = np.array([10, 20, 30, 40, 50])

# Index with list
print(arr[[0, 2, 4]])  # [10, 30, 50]

# Boolean indexing
mask = arr > 25
print(arr[mask])       # [30, 40, 50]

Practice Problems

  1. Extract diagonal from matrix
  2. Get even rows from 2D array
  3. Use boolean mask to filter values
  4. Replace negative values with zero
  5. Select random subset of array elements

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →