NumPy Lesson 5 – Indexing & Slicing | Dataplexa

Indexing and Slicing in NumPy

In real-world data analysis, you rarely work with an entire dataset at once. Instead, you often need specific values, rows, columns, or ranges of data.

NumPy provides powerful and flexible ways to access data using indexing and slicing.


Understanding Indexing

Indexing allows you to access individual elements in an array. NumPy uses zero-based indexing, meaning the first element starts at index 0.

import numpy as np

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

Output:

10
40

Here, arr[0] returns the first element and arr[3] returns the fourth element.


Negative Indexing

Negative indexing allows you to access elements from the end of the array.

print(arr[-1])
print(arr[-2])

Output:

50
40

-1 always refers to the last element in the array.


Slicing a One-Dimensional Array

Slicing allows you to extract a range of values. The syntax is:

array[start : end]

The end index is excluded.

print(arr[1:4])

Output:

[20 30 40]

This extracts elements from index 1 up to (but not including) index 4.


Slicing with Step Size

You can also specify a step value to skip elements.

print(arr[0:5:2])

Output:

[10 30 50]

This selects every second element in the given range.


Indexing a Two-Dimensional Array

For 2D arrays, indexing follows the format:

array[row_index, column_index]

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

print(matrix[1, 2])

Output:

6

This accesses the value in the second row and third column.


Slicing Rows and Columns

You can slice rows and columns together using ranges.

print(matrix[:, 1])
print(matrix[0:2, :])

Output:

[2 5 8]
[[1 2 3]
 [4 5 6]]

Modifying Values Using Indexing

NumPy allows direct modification of array values using indexing.

arr[2] = 99
print(arr)

Output:

[10 20 99 40 50]

This feature makes NumPy efficient for data manipulation.


Practice Exercise

Exercise

Create a 3×3 NumPy array and:

  • Access the center element
  • Extract the first row
  • Extract the last column
  • Change one value using indexing

Expected Outcome

You should be able to confidently extract and modify data using indexing and slicing.


What’s Next?

In the next lesson, you will learn about Boolean Indexing, which allows filtering data using conditions.