2
votes

I am trying to understand a specific part of this article.

The definition of advanced indexing means that x[(1,2,3),] is fundamentally different than x[(1,2,3)]. The latter is equivalent to x[1,2,3] which will trigger basic selection while the former will trigger advanced indexing. Be sure to understand why this occurs.

I have experimented with the following code.

>>> import numpy as np 
>>> a = np.arange(50).reshape(5,10)    
>>> b = a[(2,2)]    
>>> bb = a[(2,2),]    
>>> a[2,2] = 50 # a[2,2] was 22 in the first place 
>>> b
22  # this outcome confuses me!

I think b = a[(2,2)] would get a view so when I change a[2,2] this would do so.

bb = a[(2,2),] would receive the copy so nothing would happen even if I do something on a.

But as I change a[2,2] from 22 to 50

What I expect b = a[(2,2)] would change to 50 a and bb = a[(2,2),] is going to remain the same.

What's wrong with all of this? Am I misunderstanding or missing something important?

If it is, Please correct me and thank in advance!

1

1 Answers

0
votes

"Basic selection" (i.e. indexing as opposed to slicing) doesn't create a view, it creates a copy. In order to be a view, you need to pass a one-element slice (slicing, unlike indexing, is always a view).

import numpy as np 
a = np.arange(50).reshape(5,10)    
b = a[2:3,2:3].squeeze()    
a[2,2] = 50 
b

array(50)

You can also get the same thing with b = a[2, 2, None].squeeze(), which triggers "fancy" indexing," which is a sort of a hybrid between selection and slicing and reurns a view. Using "advanced" indexing (as you did, or like b = a[[2],[2]]) is a variant of indexing, and returns a copy.

And yes, keeping those various types of indexing straight isn't easy for beginners. And creating a view of one element is still kind of hacky. A 0-dim array like array(50) can be used in most cases like a normal int.

To make it even more confusing, a[2,2] is interpreted as a view when on the left side of an equals sign, but not on the right. It has to do with = being interpreted as .__setitem__().