Broadcasting And Copy

Numpy arrays differ from a normal Python list because of their ability to broadcast . Essentially broadcast allows users to select a chunk of the array using slicing notation and broadcast ( change ) their values to something else. Let us understand this with the help of an example.


In the code below , i have an array of 10 integers and i want to change the values of first integers of the array to 100.

import numpy as np
my_arr = np.arange(0,10)
my_arr[:5] = 100  #broadcasting
print(my_arr)
Output :
[100 100 100 100 100   5   6   7   8   9]
Note that in broadcasting if one array is assigned to a another array , then any broadcasting of elements in either of the array will affect both the arrays. Example given below is based on this.
import numpy as np
my_arr = np.arange(0,10)
my_new_arr = my_arr[:5]
my_new_arr[:5] = 98
print(my_arr)
Output :
[98 98 98 98 98  5  6  7  8  9]
Notice how there was no broadcasting for elements in my_arr but it certainly had the effect of the broadcasting in my_new_arr. This means that the data is never copied and this new array is simply a 'reference' to the original array.

To solve this problem , we need to specify numpy that we want to create a copy of the older array instead of just making references to them. This is where we use the copy method. Let us understand this with help of an example.

import numpy as np
my_arr = np.arange(0,10)
my_new_arr = my_arr.copy()
my_new_arr [:] = 100   # all elements broadcasted to 100
print(my_new_arr)
print(my_arr)
Output :
[100 100 100 100 100 100 100 100 100 100]
[0 1 2 3 4 5 6 7 8 9]

This way we have successfully performed broadcasting on the new array without affecting the original array.





Popular Tutorials

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.