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?
mat[0, :]androw1[0]modify the original array butmat[[0], :]androw1[0, 0]do not. Right?mat[[2], :]=-9will work. That's because the assignment is part of the indexing, not a separate step as withrow3.mat.__setitem__(([2],slice(None), -9).row3uses a__getitem__().