7/26
Part 2 of 4 · BroadcastingLearn
Broadcasting: a small array stretches to fit the table
You can add a smaller array to the table, or subtract one from it. NumPy acts as if it copies the small array until it is as big as the table, then works number by number. That copying is called broadcasting. NumPy never really makes the copies in memory, but picture it that way.
The teacher gives bonus points: 5 on test 1, none on test 2, 10 on test 3. Every student gets the same bonus, so the bonus is one number per test.
scores (2, 3)test 1test 2test 3AnaBen
+
bonus (3,) stretched to (2, 3)=
result (2, 3)
test 1test 2test 3AnaBen
Ben, test 3: 60 + 10 = 70. The 10 is the test 3 bonus.
real numbers copies NumPy acts as if it madeTap a cell to see where its numbers come from.
The 3 bonus numbers sit under the 3 tests. NumPy copies them down onto every student's row, then adds. In code:
# one number per test
bonus = np.array([5, 0, 10])
print(scores + bonus)
[[ 75 80 100]
[ 55 100 70]]