Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about when NumPy array slices are references and when they are copies

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?

like image 457
Vlad Dinu Avatar asked Nov 05 '18 14:11

Vlad Dinu


People also ask

Are numpy arrays passed by reference or value?

Python does not pass-by-reference nor pass-by-value.

How does numpy array slicing work?

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.

Are numpy arrays copied?

The array. copy() method in numpy is used to make and change an original array, and returns the two arrays.

Does changing a slice of a numpy array affect the original array?

Sliced numpy array does not modify original array.


1 Answers

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.

like image 175
user2699 Avatar answered Sep 30 '22 10:09

user2699