1

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?

2
  • So what you are really asking is why mat[0, :] and row1[0] modify the original array but mat[[0], :] and row1[0, 0] do not. Right? Commented May 29, 2022 at 13:17
  • mat[[2], :]=-9 will work. That's because the assignment is part of the indexing, not a separate step as with row3. mat.__setitem__(([2],slice(None), -9). row3 uses a __getitem__(). Commented May 29, 2022 at 15:57

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.