Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

NumPy Broadcast(Broadcast)

NumPy Broadcast(Broadcast)

Broadcast is the way numpy performs numerical calculations on arrays of different shapes; arithmetic operations on arrays are usually performed on the corresponding elements.

If two arrays a and b have the same shape, i.e. satisfying a.shape == b.shape, then the result of a*b is the multiplication of the corresponding positions of arrays a and b. This requires the same number of dimensions and the same length in each dimension.

Example

import

numpy

as

np

a

=

np

.

array

(

[

1

,

2

,

3

,

4

]

)

b

=

np

.

array

(

[

10

,

20

,

30

,

40

]

)

c

=

a

b

print

(

c

)

The output is:

[ 10  40  90 160]

When the two arrays in an operation have different shapes, numpy automatically triggers the broadcasting mechanism. For example:

Example

import

numpy

as

np

a

=

np

.

array

(

[

[

0

,

0

,

0

]

,

[

10

,

10

,

10

]

,

[

20

,

20

,

20

]

,

[

30

,

30

,

30

]

]

)

b

=

np

.

array

(

[

0

,

1

,

2

]

)

print

(

a

b

)

The output is:



[[ 0  1  2]

 [10 11 12]

 [20 21 22]

 [30 31 32]]

The following picture shows how array b is made compatible with array a through broadcasting.

Adding a 4x3 two-dimensional array to a one-dimensional array of length 3 is equivalent to repeating array b 4 times in two dimensions before the operation:

Example

import

numpy

as

np

a

=

np

.

array

(

[

[

0

,

0

,

0

]

,

[

10

,

10

,

10

]

,

[

20

,

20

,

20

]

,

[

30

,

30

,

30

]

]

)

b

=

np

.

array

(

[

1

,

2

,

3

]

)

bb

=

np

.

tile

(

b

,

(

4

,

1

)

)

Repeat each dimension of b

print

(

a

bb

)

The output is:

[[ 1  2  3]

 [11 12 13]

 [21 22 23]

 [31 32 33]]

Broadcasting rules:

**Simple understanding:** For two arrays, compare each of their dimensions separately (if one array does not have the current dimension, ignore it), satisfying:

If the conditions are not met, raise "ValueError: frames are not aligned" exception.