Advertisement
elena1234

Broadcasting reassignment in Python / Be careful!

Apr 14th, 2022
1,219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. import numpy as np
  2.  
  3. myarray = np.arange(0, 11)
  4. print(myarray)  # [ 0  1  2  3  4  5  6  7  8  9 10]
  5.  
  6. myarray[0:4] = 100  # Broadcasting reassignment. Be careful!
  7. print(myarray)  # [100 100 100 100   4   5   6   7   8   9  10]
  8.  
  9. slice_of_array = myarray[0:5]
  10. print(slice_of_array)  # [100 100 100 100  4]
  11. print(myarray)  # [100 100 100 100   4   5   6  ]
  12.  
  13. slice_of_array[:] = 200
  14. print(myarray)  # [200 200 200 200 200   5   6   7   8   9  10]
  15.  
  16.  
  17. # To avoid above:
  18. arr_copy = myarray.copy() # NB!
  19. slice_simple = arr_copy[0:5]
  20. slice_simple[:] = 900
  21. print(slice_simple)  # [900 900 900 900 900]
  22. print(arr_copy) # [900 900 900 900 900   5   6   7   8   9  10]
  23. print(myarray)  # [200 200 200 200 200   5   6   7   8   9  10]
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement