Learn NumPy · 4/15

Basic Indexing and Slicing: Accessing Your Data

6 min read

📝 Basic Indexing and Slicing: Accessing Your Data

Welcome! So you've got your data in a NumPy array, which is fantastic. But how do you get to the specific bits and pieces you need? It's like having a giant warehouse full of goodies, but you need a map and a forklift to grab what you want. That's where indexing and slicing come in. They are the fundamental tools for accessing and manipulating your data within NumPy arrays.

The Problem: Imagine you have a massive dataset, say, the daily temperatures for the last year. You might want to find the temperature on a specific day, or maybe you need to analyze the temperatures for a particular month. Without a precise way to access this data, you'd be lost in a sea of numbers.

The Solution: NumPy provides powerful and intuitive ways to select specific elements or subsections of your arrays. This guide will walk you through the most common and practical techniques you'll use daily.


1. 1D Array Indexing: Familiar Ground (Like Python Lists) 🕵️‍♀️

If you've worked with Python lists, you're already on familiar ground. Indexing a one-dimensional NumPy array is just like indexing a list.

The Core Idea: Every element in a 1D array has a specific position, called an index. The first element is at index 0, the second at index 1, and so on.

Let's see it in action:

python
import numpy as np

# Let's create a 1D array of lottery numbers
lottery_numbers = np.array([4, 8, 15, 16, 23, 42])

# Get the first number (at index 0)
first_number = lottery_numbers[0]
print(f"The first lottery number is: {first_number}")

# Get the third number (at index 2)
third_number = lottery_numbers[2]
print(f"The third lottery number is: {third_number}")

🤯 Fun Fact: This zero-based indexing is a common convention in many programming languages, including C, which is what NumPy is built on for performance!

Negative Indexing: The "Back of the Line" Trick

What if you want the last element, but you don't know how long the array is? No problem! You can use negative indices. [-1] gets you the last element, [-2] the second to last, and so on.

python
# Get the last lottery number
last_number = lottery_numbers[-1]
print(f"The last lottery number is: {last_number}")

# Get the second to last number
second_to_last = lottery_numbers[-2]
print(f"The second to last number is: {second_to_last}")

2. 2D Array Indexing: Navigating Rows and Columns with [row, col] 🗺️

Now, let's level up to two-dimensional arrays, which are like spreadsheets or grids. To pinpoint an element, you need two coordinates: its row and its column.

The Core Idea: You use the syntax array[row, column] to access an element in a 2D array. Remember, both row and column indices start at 0.

Imagine a 2D array representing a movie theater's seating chart.

python
# 0 represents an empty seat, 1 represents a taken seat
seating_chart = np.array([
    [1, 0, 1, 0],
    [0, 1, 1, 0],
    [1, 1, 0, 1]
])

# Is the seat in the first row, second column taken? (row 0, col 1)
seat_status = seating_chart[0, 1]
print(f"Seat at [0, 1] is taken: {bool(seat_status)}")

# Let's check the seat in the third row, fourth column (row 2, col 3)
seat_status_2 = seating_chart[2, 3]
print(f"Seat at [2, 3] is taken: {bool(seat_status_2)}")

A Tale of Two Syntaxes: While array[row, col] is the standard and most efficient way, you might sometimes see array[row][col]. The latter creates a temporary intermediate array and is less performant, so it's best to stick with the comma-separated syntax.


3. Slicing 1D Arrays: The start:stop:step Pattern 🍰

What if you want a piece of your array, not just a single element? This is where slicing comes in, and it's incredibly powerful.

The Core Idea: Slicing lets you grab a sub-section of an array using the pattern start:stop:step.

  • start: The index where the slice begins (inclusive). If omitted, it defaults to the beginning of the array.
  • stop: The index where the slice ends (exclusive). If omitted, it goes to the end of the array.
  • step: The interval between elements. If omitted, it defaults to 1.

Let's go back to our lottery numbers:

python
lottery_numbers = np.array([4, 8, 15, 16, 23, 42])

# Get the first three numbers (indices 0, 1, and 2)
first_three = lottery_numbers[0:3]
print(f"The first three numbers are: {first_three}")

# A shorter way to get the first three
first_three_short = lottery_numbers[:3]
print(f"First three (shorter syntax): {first_three_short}")

# Get all numbers from the third element to the end
from_third_on = lottery_numbers[2:]
print(f"From the third number onwards: {from_third_on}")

# Get every other number
every_other = lottery_numbers[::2]
print(f"Every other number: {every_other}")

The "View" vs. "Copy" Distinction: A Word of Caution!

This is a crucial concept. When you slice a NumPy array, you get a view of the original array, not a copy. This means that if you modify the slice, the original array is also modified! This is great for memory efficiency, but can lead to unexpected behavior if you're not aware of it.

python
# Create an array of temperatures
temperatures = np.array([68, 72, 75, 80, 82])

# Create a slice of the middle three temperatures
mid_temps = temperatures[1:4]
print(f"Original middle temperatures: {mid_temps}")

# Now, let's say a heatwave hits and we update the slice
mid_temps[1] = 95
print(f"Modified middle temperatures: {mid_temps}")

# Look what happened to the original array!
print(f"Original temperatures after modification: {temperatures}")

If you want a separate copy, you need to explicitly use the .copy() method.

python
# Create a copy to avoid modifying the original
mid_temps_copy = temperatures[1:4].copy()

4. Slicing Multi-Dimensional Arrays: Grabbing Sub-matrices 🧱

The power of slicing extends to multi-dimensional arrays, allowing you to select entire rows, columns, or sub-regions of your data.

The Core Idea: You apply the start:stop:step pattern to each dimension, separated by commas.

Let's use our seating chart again:

python
seating_chart = np.array([
    [1, 0, 1, 0],
    [0, 1, 1, 0],
    [1, 1, 0, 1]
])

# Get the entire first row
first_row = seating_chart[0, :]  # or just seating_chart[0]
print(f"The first row:\n{first_row}")

# Get the second column
second_col = seating_chart[:, 1]
print(f"The second column:\n{second_col}")

# Get a 2x2 sub-matrix from the top-left corner
top_left_corner = seating_chart[:2, :2]
print(f"The top-left 2x2 corner:\n{top_left_corner}")

Pro-Tip: The colon : by itself means "select everything in this dimension". This is a very common and useful shorthand.

By mastering these basic indexing and slicing techniques, you've unlocked the ability to navigate and manipulate your NumPy arrays with precision and efficiency. These are the foundational skills you'll build upon as you delve deeper into the world of numerical computing with Python!

📚 References

Challenge

You are given a 2D NumPy array named sensor_data representing a 5x5 grid of temperature readings. Your task is to perform a series of indexing and slicing operations to extract and manipulate subsets of this data. Do not modify the initial sensor_data array directly, except as specified by the view modification task.

  1. Select a 3x3 sub-grid from the center of sensor_data (rows 1-3, columns 1-3). Assign the result to a variable named center_grid.
  2. Extract all readings from the last row (index 4) of sensor_data. Assign this 1D array to last_interval_readings.
  3. Extract all readings from the second column (index 1) of sensor_data. Assign this 1D array to sensor_two_readings.
  4. Create a view of the top-left 2x2 sub-grid of sensor_data. Assign this view to top_left_view. Then, modify the element at index [1, 1] of top_left_view to have a value of 99.0.
  5. Create an independent copy of the bottom-right 3x2 sub-grid (last 3 rows, last 2 columns). Assign this new array to bottom_right_copy. Then, modify the element at index [0, 0] of bottom_right_copy to have a value of -1.0.
  6. Using a single slicing operation, extract a new array containing all values from the first four rows, but only from the columns with even indices (0, 2, 4). Assign the result to alternating_sensor_readings.

Expected result

Your code should correctly initialize six variables. After your script runs:

  • center_grid should be a 3x3 NumPy array with the value:
    lua
    [[22.2, 22.5, 23.1],
     [25.4, 25.8, 26.1],
     [25.1, 25.5, 25.9]]
  • last_interval_readings should be a 1D array with the value [20.1, 20.5, 20.9, 21.4, 21.8].
  • sensor_two_readings should be a 1D array with the value [23.1, 22.2, 25.4, 25.1, 20.5].
  • Because top_left_view is a view, the modification to it will also change the original sensor_data array. The final state of sensor_data should be:
    inform7
    [[22.5, 23.1, 22.8, 23.5, 24.0],
     [21.9, 99. , 22.5, 23.1, 23.6],
     [25.0, 25.4, 25.8, 26.1, 26.3],
     [24.8, 25.1, 25.5, 25.9, 26.2],
     [20.1, 20.5, 20.9, 21.4, 21.8]]
  • bottom_right_copy should be a 3x2 NumPy array. Because it is a copy, the modification to it does not affect sensor_data. Its value should be:
    lua
    [[-1. , 26.3],
     [25.9, 26.2],
     [21.4, 21.8]]
  • alternating_sensor_readings should be a 4x3 NumPy array with the value:
    inform7
    [[22.5, 22.8, 24. ],
     [21.9, 22.5, 23.6],
     [25. , 25.8, 26.3],
     [24.8, 25.5, 26.2]]
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.