Reputation: 363
I was reviewing some numpy code and came across this issue. numpy is exhibiting different behavior for 1-d array and 2-d array. In the first case, it is creating a reference while in the second, it is creating a deep copy.
Here's the code snippet
import numpy as np
# Case 1: when using 1d-array
arr = np.array([1,2,3,4,5])
slice_arr = arr[:3] # taking first three elements, behaving like reference
slice_arr[2] = 100 # modifying the value
print(slice_arr)
print (arr) # here also value gets changed
# Case 2: when using 2d-array
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
slice_arr = arr[:,[0,1]] # taking all rows and first two columns, behaving like deep copy
slice_arr[0,1] = 100 # modifying the value
print(slice_arr)
print() # newline for clarity
print (arr) # here value doesn't change
Can anybody explain the reason for this behavior?
Upvotes: 1
Views: 76
Reputation: 22033
The reason is that you are not slicing in the same way, it's not about 1D vs 2D.
slice_arr = arr[:3]
Here you are using the slicing operator, so numpy can make a view on your original data and returns it.
slice_arr = arr[:,[0,1]]
Here you are using a list of elements you want, and it's not a slice (even if it could be represented by a slice), in that case, numpy returns a copy.
All these are getters, so they can return either view or copy.
For setters, it's always modifying the current array.
Upvotes: 4