Mathew K Analytics

Lesson 24 · Python for Data Science

02 NumPy Indexing: Learn Array Access and Manipulation in Python

NumPy lets us work with large sets of numbers quickly and easily. Today you will learn how to select, change, and use data in NumPy arrays. You do not need…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Welcome to NumPy Indexing for Absolute Beginners!#

NumPy lets us work with large sets of numbers quickly and easily.

Today you will learn how to select, change, and use data in NumPy arrays.

You do not need to have used NumPy before.

Get ready to build the skills you need for science, data, and more.

Step 1: Importing NumPy#

Before we can use NumPy, we need to import it into our code.

It is common to use the nickname np so we type less.

import numpy as np
# Now we can use 'np' to work with NumPy arrays!
numbers = np.array([10, 20, 30, 40, 50])
print(numbers)

# This is a basic NumPy array!
[10 20 30 40 50]

Step 2: What is Indexing?#

Indexing means picking out values from an array by telling Python which spot we want.

In NumPy, indexing is super fast. We start counting from zero.

first_value = numbers[0]
print('The first value is:', first_value)
The first value is: 10
third_value = numbers[2]
print('The third value is:', third_value)

# Remember: counting starts at zero!
The third value is: 30
last_value = numbers[-1]
print('The last value is:', last_value)

# Negative indexes count from the end.
The last value is: 50
print(numbers[1:4])  # This means spots 1 up to, but not including, 4.

# This is called a slice!
[20 30 40]
every_other = numbers[::2]
print('Every other value:', every_other)

# The double colon lets us skip values.
Every other value: [10 30 50]

Step 3: Indexing with 2D Arrays#

NumPy can make arrays with more than one row.

Indexing works a little differently: we pick row and column.

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

# This is a '2D array' or a 'matrix'.
[[1 2 3]
 [4 5 6]
 [7 8 9]]
print(grid[1, 2])

# This grabs row 1, column 2.
6
print(grid[:, 0])

# Colon means all rows of column zero.
[1 4 7]
# Let us try changing a value in the array.
grid[0, 1] = 42
print(grid)

# NumPy arrays let us update spots directly!
[[ 1 42  3]
 [ 4  5  6]
 [ 7  8  9]]
# Indexing works with input too.
chosen_row = int(input('Pick a row number (0-2): '))
chosen_column = int(input('Pick a column number (0-2): '))
value = grid[chosen_row, chosen_column]
print('You selected:', value)
You selected: 8
 

Step 4: Boolean Indexing#

We can use True and False to select values based on condition.

This is called boolean (boo-lee-an) indexing.

big_numbers = numbers[numbers > 25]
print('Numbers bigger than 25:', big_numbers)

# This builds a new array with only values that match.
Numbers bigger than 25: [30 40 50]
print(grid[grid % 2 == 0])

# This finds all even numbers in our grid.
[42  4  6  8]

Step 5: Fancy Indexing#

Fancy indexing means using a list of numbers to pick out any positions you want.

This is very fast and makes NumPy powerful.

special = numbers[[1, 3, 4]]
print('Picked spots:', special)

# We selected the second, fourth, and fifth values.
Picked spots: [20 40 50]
# You can also combine fancy and boolean indexing.
odd_rows = grid[[0, 2], :]  # Pick rows 0 and 2
print('Odd rows only:', odd_rows)
Odd rows only: [[ 1 42  3]
 [ 7  8  9]]
# Let us sort an array with NumPy.
shuffled = np.array([5, 2, 7, 1, 3])
sorted_array = np.sort(shuffled)
print('Sorted:', sorted_array)
# Sorting helps us organize data.
Sorted: [1 2 3 5 7]
# Filtering for values greater than three in a 2D array.
greater_than_three = grid[grid > 3]
print('Values over three:', greater_than_three)
Values over three: [42  4  5  6  7  8  9]
# Combining data using NumPy.
extra = np.array([100, 200, 300, 400, 500])
combined = np.concatenate((numbers, extra))
print('Combined arrays:', combined)
Combined arrays: [ 10  20  30  40  50 100 200 300 400 500]

Step 6: Mini Project - Student Test Scores#

Let us use our new skills in a short project.

Imagine we have test scores from three students on four tests.

scores = np.array([[88, 92, 85, 90],
                 [76, 95, 89, 91],
                 [84, 87, 93, 89]])
print(scores)

# Each row is one student. Each column is one test.
[[88 92 85 90]
 [76 95 89 91]
 [84 87 93 89]]
# Let us find the highest score for each student.
best_scores = np.max(scores, axis=1)
print('Best score per student:', best_scores)
Best score per student: [92 95 93]
# Challenge: Get all test scores above ninety.
above_ninety = scores[scores > 90]
print('All scores above ninety:', above_ninety)
All scores above ninety: [92 95 91 93]
# Common mistake: Out of range index.
try:
    bad_value = numbers[12]
except IndexError as e:
    print('Oops:', e)
    
Oops: index 12 is out of bounds for axis 0 with size 5

Step 7: Final Tips#

  • Indexing is key to almost everything in NumPy!
  • Practice with your own arrays and slices.
  • If you get errors, check your index numbers.
  • For more, try searching for 'NumPy array indexing' online.

Congratulations! You have built a strong foundation.

Thanks for Learning!#

If you liked this video, please hit Like, leave a Comment about what you learned, and Subscribe for more lessons.

Share this video with a friend who wants to learn programming!

Happy coding with NumPy!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.