What is Broadcasting in NumPy?

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations.

General rules for Broadcasting

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions and works its way forward. Two dimensions of size N are compatible when

  1. they are equal, or
  2. one of them is the singular value
  3. one is N * N and other is N * 1
  4. one is N * N and other is 1 * N

Examples

The concept of broadcasting is explained through code and figure in the following examples:-

When one operand is N*N and other is 1 * 1

Z1 = np.arange(9).reshape(3,3)
Z2 = 1 
Z1 + Z2
  
   ┌───┬───┬───┐   ┌───┐   ┌───┬───┬───┐   ┏━━━┓───┬───┐   ┌───┬───┬───┐
   │ 0 │ 1 │ 2 │ + │ 1 │ = │ 0 │ 1 │ 2 │ + ┃ 1 ┃ 1 │ 1 │ = │ 1 │ 2 │ 3 │
   ├───┼───┼───┤   └───┘   ├───┼───┼───┤   ┗━━━┛───┼───┤   ├───┼───┼───┤
   │ 3 │ 4 │ 5 │           │ 3 │ 4 │ 5 │   │ 1 │ 1 │ 1 │   │ 4 │ 5 │ 6 │
   ├───┼───┼───┤           ├───┼───┼───┤   ├───┼───┼───┤   ├───┼───┼───┤
   │ 6 │ 7 │ 8 │           │ 6 │ 7 │ 8 │   │ 1 │ 1 │ 1 │   │ 7 │ 8 │ 9 │ 
   └───┴───┴───┘           └───┴───┴───┘   └───┴───┴───┘   └───┴───┴───┘


Get hands-on with 1200+ tech skills courses.