Home > Software engineering >  Difference between slicing of a numpy array
Difference between slicing of a numpy array

Time:05-30

So, mat is a NumPy array and I create different views from the array using slicing operation, with different rows as row1, row2, row3.

Then I try to modify each row, but why am I not able to modify the actual array mat in case of row3?

mat = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
row1 = mat[0, :] #[1 2 3 4] 
row2 = mat[1:2, :] #[[5 6 7 8]]
row3 = mat[[2], :] #[[ 9 10 11 12]]
row1[0] = -1 #[-1  2  3  4] 
row2[0,0] = -5 #[[-5  6  7  8]] 
row3[0,0] = -9 # [[-9 10 11 12]]
print(mat)

The output in this case is

[[-1  2  3  4]
 [-5  6  7  8]
 [ 9 10 11 12]]

Why is row3 not referencing to the original array?

CodePudding user response:

the indexing operation you are doing on row3 is considered advanced_indexing, numpy will always create copies during advanced indexing and views during normal indexing

  • Related