3️⃣ 🎯 NumPy Array Access & Manipulation
Estimated reading: 3 minutes 23 views

🧱 NumPy Array Indexing – Accessing Elements Efficiently

🧲 Introduction – Why Learn Array Indexing in NumPy?

Indexing is the foundation of data access in NumPy. Whether you’re extracting single values, slicing subarrays, or filtering data using conditions, indexing allows precise control over your array operations. Mastering array indexing not only simplifies your code but also boosts performance, especially with large datasets.

🎯 In this guide, you’ll learn:

  • The basics of 1D, 2D, and 3D indexing
  • How slicing, integer arrays, and boolean masks work
  • Advanced indexing techniques with multiple dimensions
  • Real-world use cases and best practices

🔢 Basic Indexing – 1D Arrays

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[0])   # Access first element
print(arr[-1])  # Access last element

👉 Output:

10  
50

📌 You can use positive or negative indices. Indexing starts at 0.


🧮 Indexing in 2D Arrays

arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d[0, 2])  # 1st row, 3rd column
print(arr2d[1][0])  # 2nd row, 1st column

👉 Output:

3  
4

📌 Use [row, col] format or chained indexing (arr2d[row][col]).


🧊 Indexing in 3D Arrays

arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr3d[1, 0, 1])  # 2nd block, 1st row, 2nd column

👉 Output:

6

📌 Format: [depth, row, col]


✂️ Slicing Arrays – start:stop:step

arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])      # Elements from index 1 to 3
print(arr[::2])      # Every second element
print(arr[::-1])     # Reverse the array

👉 Output:

[20 30 40]  
[10 30 50]  
[50 40 30 20 10]

📌 Omitting start or stop uses default (start=0, stop=end)


🧠 Boolean Indexing (Masking)

arr = np.array([1, 2, 3, 4, 5])
mask = arr > 3
print(arr[mask])

👉 Output:

[4 5]

📌 Useful for filtering elements based on conditions


🔢 Integer Array Indexing

arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3, 4]
print(arr[indices])

👉 Output:

[20 40 50]

📌 Allows non-contiguous or repeated element selection


🔄 Multi-Dimensional Slicing

arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr2d[:2, 1:])  # Rows 0–1, Columns 1–2

👉 Output:

[[2 3]  
 [5 6]]

📌 Combine row and column slicing using commas


🔁 Using ellipsis (...) for Simplified Access

arr3d = np.arange(27).reshape(3, 3, 3)
print(arr3d[0, ..., 2])  # First block, all rows, 3rd column

👉 Output:

[2 5 8]

📌 ... replaces as many colons as needed


⚠️ Common Pitfalls

  • ❌ Using too many or too few indices for array dimension
  • ❌ Mixing boolean and integer indexing in the same axis
  • ❌ Index out of bounds

Example:

arr = np.array([1, 2, 3])
print(arr[5])  # ❌ IndexError

📊 Indexing Techniques Comparison

TechniqueDescriptionExample
Basic indexingAccess by positionarr[1]
SlicingRange of valuesarr[1:4]
Integer array indexingSpecific indicesarr[[0, 2]]
Boolean indexingCondition-based selectionarr[arr > 5]
Multi-axis indexingFor 2D/3D+ arraysarr[0, 1]
Ellipsis indexingFill missing dimensionsarr[..., 0]

🔍 Summary – Key Takeaways

  • Use indexing to access, modify, and filter NumPy arrays efficiently
  • Master 1D, 2D, and 3D indexing to handle complex data
  • Combine slicing with conditions for dynamic selection
  • Indexing is read/write: you can assign values directly using slices or masks

⚙️ Real-World Applications

  • Extract rows/columns from datasets
  • Filter time series or sensor readings
  • Select specific image channels or pixels
  • Prepare feature matrices for ML models

❓ FAQs – NumPy Array Indexing

❓ Can I assign values using slicing?
✅ Yes:

arr[1:3] = [100, 200]

❓ What happens if I use a mask of the wrong size?
✅ You’ll get an error. The boolean mask must match the array’s shape.

❓ Can I combine slicing and boolean indexing?
❌ Not directly on the same axis. Use intermediate arrays.

❓ Is slicing a view or a copy?
✅ Slicing returns a view (modifies original), while integer/boolean indexing returns a copy.

❓ How do I reverse an array?
✅ Use slicing:

arr[::-1]

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

NumPy Array Indexing

Or Copy Link

CONTENTS
Scroll to Top