Broadcasting

Introduzione a NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

Broadcasting introduced

 

A graphic showing two arrays with different shapes begin added together

Introduzione a NumPy

Broadcasting a scalar

Image showing a 2D array being added to the number 2  

Image showing a 2D array being added to any array full of twos which has the same shape

Introduzione a NumPy

Compatibility rules

  • NumPy compares sets of array dimensions from right to left  

 

 

 

 

A graphic applying the compatibility rules to arrays shapes of (10, 5 and (10, 1))

Introduzione a NumPy

Compatibility rules

  • NumPy compares sets of array dimensions from right to left
  • Two dimensions are compatible when...
    • One of them has a length of one or
    • They are of equal lengths
  • All dimension sets must be compatible

 

A graphic applying the compatibility rules to arrays shapes of (10, 5 and (10, 1))

Introduzione a NumPy

Broadcastable or not?

 

Broadcastable shapes:

  • (10, 5) and (10, 1)
  • (10, 5) and (5, )

 

Shapes which are not broadcastable:

  • (10, 5) and (5, 10)
  • (10, 5) and (10, )
Introduzione a NumPy

Broadcasting rows

An array with shape (2, 5) being added to an array with shape (1, 5)

 

array = np.arange(10).reshape((2, 5))
array + np.array([0, 1, 2, 3, 4])
array([[ 0,  2,  4,  6,  8],
       [ 5,  7,  9, 11, 13]])
Introduzione a NumPy

Broadcasting rows

 

 

An array with shape (2, 5) being added to an array with shape (2, 5)

Introduzione a NumPy

Incompatible broadcasting

 

A graphic showing that adding an array of shape (2, 5) to one of shape (2,) generates a ValueError.

 

array = np.arange(10).reshape((2, 5))
array + np.array([0, 1])
ValueError: operands could not be broadcast together with shapes (2,5) (2,) 
Introduzione a NumPy

Broadcasting columns

A graphic showing an array of shape (2, 5) and one of shape (2, 1) being added together

array = np.arange(10).reshape((2, 5))
array + np.array([0, 1]).reshape((2, 1))
array([[ 0,  1,  2,  3,  4],
       [ 6,  7,  8,  9, 10]])
Introduzione a NumPy

Broadcasting columns

 

 

A graphic showing the single-column array stretched column-wise across an array with the same shape as the larger array

Introduzione a NumPy

Other operators

An array with shape (2, 2) being multiplied by an array with shape (2, 1)

An array with shape (2, ) being subtracted from an array with shape (2, 2)

Introduzione a NumPy

Let's practice!

Introduzione a NumPy

Preparing Video For Download...