I have the following piece of code:
import numpy as np
arr = np.arange(10)
slice = arr[2:5]
slice[:] = 12
print(arr)
slice = slice / 2
print(arr)
The output will be:
[ 0 1 12 12 12 5 6 7 8 9]
[6. 6. 6.]
[ 0 1 12 12 12 5 6 7 8 9]
So the first time around slice
is just a reference to part of arr
so modifying it also changes the array, but the second time around it has become a copy of that part of the array and modifying it makes no difference in arr
. Why does this happen? What makes slice = slice / 2
different?
Python does not pass-by-reference nor pass-by-value.
Indexing can be done in numpy by using an array as an index. In case of slice, a view or shallow copy of the array is returned but in index array a copy of the original array is returned. Numpy arrays can be indexed with other arrays or any other sequence with the exception of tuples.
The array. copy() method in numpy is used to make and change an original array, and returns the two arrays.
Sliced numpy array does not modify original array.
Indexing with a slice object always returns a view (reference) of an array. Modifying the slice will modify the original array. In your second example you assign to the slice object. That does not modify the object. A new object is created with the specified values, in this case slice / 2. You can use /=
to modify the object in place if that's the desired behavior, or index into the slice ([:]
) which numpy interprets as modifying the entries at those indices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With