Editor

Add Bonus Points

Advanced · Write the code · from NumPy Broadcasting: Operate on Arrays of Different Shapes

From the lesson: NumPy Broadcasting: Operate on Arrays of Different Shapes

You've already seen that np.array([1,2,3]) 2 multiplies every element by 2. But have you wondered how* NumPy knows to stretch that single number 2 across the entire array? That mechanism is called broadcasting.

Read the lesson

A teacher has a 3x4 grades matrix and wants to add different bonus points to each exam (column). The bonus array is [5, 3, 8, 2]. Use broadcasting to add the bonus to all students at once. Print the result.

grades = np.array([[70, 85, 60, 90],
                   [80, 75, 85, 70],
                   [90, 95, 70, 80]])
bonus = np.array([5, 3, 8, 2])
import numpy as np
grades = np.array([[70, 85, 60, 90],
[80, 75, 85, 70],
[90, 95, 70, 80]])
bonus = np.array([5, 3, 8, 2])
# Add bonus to grades and print

More NumPy Broadcasting exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz