Unit 24Broadcasting

numpy arrays eagerly engage in vectorized arithmetic operations with other arrays—as long as they’re of the same shape. To add two arrays element-wise without numpy, you must use a for loop or list comprehension; with numpy, you simply add them up:

 a = np.arange(4)
 b = np.arange(1, 5)
 a + b
=> array([1, 3, 5, 7])

Vectorized operations on arrays are known as broadcasting. Broadcasting along two dimensions is possible if they are equal (as above) or one of them is a scalar (as below):

 a * 5
=> array([0, 5, 10, 15])

Be Fruitful or Multiply?

images/aside-icons/important.png

The star operator (*) behaves differently in Python and numpy. The “core” Python ...

Get Data Science Essentials in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.