October 2019
Beginner to intermediate
674 pages
16h 43m
English
Using broadcasting, we can work with arrays that don't have exactly the same shape. Here is an example:
In [357]: ar=np.ones([3,2]); ar
Out[357]: array([[ 1., 1.],
[ 1., 1.],
[ 1., 1.]])
In [358]: ar2=np.array([2,3]); ar2
Out[358]: array([2, 3])
In [359]: ar+ar2
Out[359]: array([[ 3., 4.],
[ 3., 4.],
[ 3., 4.]])
Thus, we can see that ar2 is broadcast across the rows of ar by adding it to each row of ar, producing the preceding result. Here is another example, showing that broadcasting works across dimensions:
In [369]: ar=np.array([[23,24,25]]); ar
Out[369]: array([[23, 24, 25]])
In [368]: ar.T
Out[368]: array([[23],
[24],
[25]])
In [370]: ar.T+ar
Out[370]: array([[46, 47, 48],
[47, 48, 49],
[48, 49, 50]])
Here, both row and ...
Read now
Unlock full access