NumPy Basics · Exercises
Data

NumPy Basics Exercises

4 exercises that build on the NumPy Basics lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: NumPy is a library that stores numbers in an array — a grid of values that all share one type — and lets you do maths on the whole array at once instead of looping over each number. By the end you can create 1-D and 2-D arrays, check their shape and dtype, do arithmetic on whole arrays, filter values with boolean masks, and summarise data with mean, sum and max along an axis. You will practise: Convert a whole array; Predict the array results; Fix the comfortable-temperature filter; Averages per student and the hardest test.

0 / 4 completed

NumPy Basics practice exercises

1. Convert a whole array

Write code Easy

Write a function to_fahrenheit(celsius) that takes a NumPy array of Celsius temperatures and returns a new NumPy array in Fahrenheit, using F = C * 9 / 5 + 32. Do it without a loop — let NumPy apply the formula to every value.

Your code
import numpy as np

week = np.array([10.0, 15.5, 20.0, 25.0])

def to_fahrenheit(celsius):
    # return a new array (no loop needed)
    pass

print(to_fahrenheit(week))

2. Predict the array results

Predict the output Easy

Read the code and type exactly what it prints. Remember that NumPy prints arrays with spaces instead of commas.

Read this code
import numpy as np

nums = np.array([6, 9, 5, 7, 8])
print(nums * 2)
print(nums[nums > 6])
print((nums > 6).sum())
print(nums.mean())

3. Fix the comfortable-temperature filter

Fix the bug Medium

comfortable(temps, low, high) should return only the temperatures between low and high (both included), but it crashes with ValueError: The truth value of an array ... is ambiguous. Fix the function so it works for any array and limits.

Your code
import numpy as np

def comfortable(temps, low, high):
    return temps[(temps >= low) and (temps <= high)]

temps = np.array([12, 18, 25, 31, 22, 9, 16])
print(comfortable(temps, 15, 25))

4. Averages per student and the hardest test

Write code Hard

scores is a 2-D array: each row is a student and each column is a test. Write two functions:

  • student_averages(scores) returns a 1-D array with each student's average score.
  • hardest_test(scores) returns the column index (an int) of the test with the lowest average.

Use mean() with the right axis, and argmin(). Both functions must work for any number of students and tests.

Your code
import numpy as np

scores = np.array([[72, 85, 60],
                   [90, 78, 55],
                   [66, 92, 70]])

def student_averages(scores):
    pass

def hardest_test(scores):
    pass

print(student_averages(scores))
print(hardest_test(scores))

Next lessonNumPy Indexing and Slicing

More NumPy Basics examples · All Python exercises