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]`

```
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]`

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