Skip to main content
Pandas & NumPy
CHAPTER 05 Beginner

NumPy Indexing and Slicing

Updated: May 18, 2026
5 min read

# CHAPTER 5

NumPy Indexing and Slicing

1. Chapter Introduction

Accessing specific elements, rows, columns, or sub-arrays from NumPy arrays is fundamental to data manipulation. NumPy provides several powerful indexing mechanisms, each suited for different access patterns.

2. Basic Indexing

python
1234567891011121314151617181920
import numpy as np

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

# Positive indexing (0-based)
print(arr[0])     # 10
print(arr[4])     # 50

# Negative indexing (from end)
print(arr[-1])    # 60
print(arr[-2])    # 50

# 2D indexing [row, col]
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])

print(matrix[0, 0])   # 1 (first row, first col)
print(matrix[1, 2])   # 6 (second row, third col)
print(matrix[-1, -1]) # 9 (last row, last col)

3. Slicing

python
123456789101112131415
arr = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

# [start:stop:step]  (stop is exclusive)
print(arr[2:6])      # [20 30 40 50]
print(arr[:4])       # [0 10 20 30]
print(arr[6:])       # [60 70 80 90]
print(arr[::2])      # [0 20 40 60 80]  (every 2nd)
print(arr[::-1])     # [90 80 70 ... 0] (reversed)

# 2D slicing [row_slice, col_slice]
matrix = np.arange(1, 26).reshape(5, 5)
print(matrix[1:4, 1:4])   # Middle 3x3 submatrix
print(matrix[:, 0])        # First column (all rows)
print(matrix[0, :])        # First row (all cols)
print(matrix[::2, ::2])    # Every other row and col

4. Boolean Indexing (Most Important!)

python
1234567891011121314151617181920
salaries = np.array([45000, 72000, 55000, 88000, 61000, 92000, 48000])
names = np.array(['Alice', 'Bob', 'Carol', 'David', 'Eve', 'Frank', 'Grace'])

# Boolean mask
mask = salaries > 60000
print(mask)          # [False True False True True True False]
print(salaries[mask])  # [72000 88000 61000 92000]
print(names[mask])     # ['Bob' 'David' 'Eve' 'Frank']

# Inline condition
high_earners = salaries[salaries > 70000]
print(high_earners)   # [72000 88000 92000]

# Multiple conditions
mid_range = salaries[(salaries >= 55000) & (salaries <= 80000)]
print(mid_range)      # [72000 55000 61000]

# NOT condition
not_low = salaries[~(salaries < 50000)]
print(not_low)        # [72000 55000 88000 61000 92000]

5. Fancy Indexing

python
1234567891011121314151617
arr = np.array([10, 20, 30, 40, 50, 60, 70, 80])

# Select by list of indices
indices = [0, 3, 6]
print(arr[indices])    # [10 40 70]

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

rows = [0, 2]
cols = [1, 0]
print(matrix[rows, cols])   # [2 7] (matrix[0,1] and matrix[2,0])

# Select specific rows
print(matrix[[0, 2]])        # First and third rows

6. Views vs Copies

python
123456789101112
arr = np.array([1, 2, 3, 4, 5])

# Slicing creates a VIEW (same memory)
view = arr[1:4]
view[0] = 99
print(arr)    # [1 99 3 4 5] — original modified!

# .copy() creates independent copy
arr = np.array([1, 2, 3, 4, 5])
copy = arr[1:4].copy()
copy[0] = 99
print(arr)    # [1 2 3 4 5] — original unchanged

7. Common Mistakes

  • View vs copy: Slices are views — modifying them modifies the original. Use .copy() when you want an independent copy.
  • Boolean indexing with OR: salaries > 60000 or salaries < 40000 fails — use | (not or) for element-wise OR.

8. MCQs

Question 1

arr[-1] accesses?

Question 2

arr[2:6] includes index?

Question 3

arr[::-1] does?

Question 4

Boolean indexing uses?

Question 5

& in NumPy boolean conditions means?

Question 6

Array slice returns?

Question 7

.copy() creates?

Question 8

matrix[:, 2] selects?

Question 9

Fancy indexing uses?

Question 10

~mask in NumPy?

9. Interview Questions

  • Q: What is the difference between a NumPy view and a copy?
  • Q: How do you select elements meeting multiple conditions in NumPy?

10. Summary

NumPy indexing covers every data access pattern: integer indexing, slicing with start:stop:step, boolean filtering with masks, and fancy indexing with index lists. Critical insight: slices are views — modify with caution, use .copy() for independence.

11. Next Chapter Recommendation

In Chapter 6: NumPy Mathematical Functions, we explore trigonometric, logarithmic, and aggregation functions for scientific computing.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·