Mastering NumPy Array Indexing in Python: A Complete Guide

Last updated 3 months, 4 weeks ago | 258 views 75     5

Tags:- Python NumPy

NumPy, short for Numerical Python, is a cornerstone of scientific computing in Python. One of its most powerful features is the ability to access and manipulate elements in arrays with ease and efficiency through indexing.

In this article, we'll explore the various ways you can index arrays using NumPy—whether you're working with one-dimensional arrays, multi-dimensional arrays, or using slicing, boolean indexing, and fancy indexing.


What Is Indexing?

Indexing is the process of accessing individual elements or groups of elements in an array using their position (index). In Python and NumPy, indices start at 0.


1. Indexing 1D Arrays

Let’s start with a simple 1D array:

import numpy as np

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

Accessing Elements

print(arr[0])    # 10
print(arr[4])    # 50
print(arr[-1])   # 50 (last element)

Modifying Elements

arr[2] = 99
print(arr)       # [10 20 99 40 50]

2. Indexing 2D Arrays

A 2D array (matrix) is indexed using row and column positions.

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

Accessing Single Elements

print(arr2d[0, 0])  # 1 (row 0, column 0)
print(arr2d[1, 2])  # 6 (row 1, column 2)
print(arr2d[-1, -1])  # 9 (last row, last column)

Modifying Elements

arr2d[0, 1] = 20
print(arr2d)

✂️ 3. Slicing Arrays

Slicing allows you to extract subarrays using the syntax: start:stop:step.

1D Slicing

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

print(arr[1:4])     # [20 30 40]
print(arr[:3])      # [10 20 30]
print(arr[::2])     # [10 30 50]

2D Slicing

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

# Extract 2x2 submatrix
print(arr2d[0:2, 0:2])

Output:

[[1 2]
 [4 5]]

4. Boolean Indexing

Select elements based on conditions.

arr = np.array([5, 10, 15, 20])

# Get all values > 10
print(arr[arr > 10])  # [15 20]

You can also assign new values:

arr[arr > 10] = 100
print(arr)  # [  5  10 100 100]

5. Fancy Indexing (Integer Indexing)

Use lists or arrays of indices to access multiple values.

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

indices = [0, 2, 4]
print(arr[indices])  # [10 30 50]

Fancy Indexing in 2D Arrays

arr2d = np.array([[1, 2], [3, 4], [5, 6]])

# Access specific elements from rows
print(arr2d[[0, 2], [1, 0]])  # [2 5]

Explanation:

  • Get element at (0,1) → 2

  • Get element at (2,0) → 5


Indexing with np.where()

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

# Get indices where condition is met
indices = np.where(arr > 20)
print(indices)       # (array([2, 3]),)
print(arr[indices])  # [30 40]

Full Working Example

import numpy as np

# Create a 2D array
data = np.array([[10, 20, 30],
                 [40, 50, 60],
                 [70, 80, 90]])

# Access elements
print("Element at (1,2):", data[1, 2])

# Slice subarray
print("First two rows:\n", data[:2, :])

# Boolean indexing
print("Elements > 50:", data[data > 50])

# Fancy indexing
rows = [0, 2]
cols = [1, 0]
print("Fancy indexed elements:", data[rows, cols])

Tips & Best Practices

Tip Why It Matters
Use slicing over loops More efficient and readable
Prefer boolean indexing for filtering It’s clean and fast
Avoid modifying slices in-place (if unsure) Slices may reference the original array
Use .copy() if you want independent data Prevents unintended changes

⚠️ Common Pitfalls

Pitfall Solution
Confusing row/column order in 2D arrays Always use arr[row, column]
Forgetting that slices are views, not copies Use .copy() if needed
Mixing up boolean vs fancy indexing Understand their behavior clearly

Conclusion

Understanding how to index arrays is essential when working with NumPy. Whether you're extracting data, filtering with conditions, or reshaping arrays, mastering indexing opens the door to powerful data manipulation.

With this guide, you now know:

  • Basic and advanced indexing

  • Slicing and subsetting

  • Boolean and fancy indexing

  • Common traps to avoid


What’s Next?

Now that you've mastered indexing, explore:

  • NumPy Array Slicing in Depth

  • Broadcasting in NumPy

  • Reshaping and Transposing Arrays

  • Vectorized Operations