Why does indexing numpy arrays with brackets and commas differ in behavior?

I tend to index numpy arrays (matrices) with brackets, but I’ve noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,

>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> x[1][1]
4                 # expected behavior
>>> x[1,1]
4                 # expected behavior
>>> x[:][1]
array([3, 4])     # huh?
>>> x[:,1]
array([2, 4, 6])  # expected behavior

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This:

x[:, 1]

means “take all indices of x along the first axis, but only index 1 along the second”.

This:

x[:][1]

means “take all indices of x along the first axis (so all of x), then take index 1 along the first axis of the result”. You’re applying the 1 to the wrong axis.

x[1][2] and x[1, 2] are only equivalent because indexing an array with an integer shifts all remaining axes towards the front of the shape, so the first axis of x[1] is the second axis of x. This doesn’t generalize at all; you should almost always use commas instead of multiple indexing steps.

Method 2

When you slice multi dimension of array, if fewer indices are provided than the number of axes, the missing indices are considered complete slices.
Hence, when you are essentially doing when calling x[:][1] is x[:,:][1,:]
Therefore, x[:,:] will just return x itself.

Method 3

The real explanation to this is in the case of 2 brackets [][], the first bracket (x[] ) creates an temporary array referring to the first dimension of the multidimensional array.

While the second bracket of the x[][] would be applied to the already created temporary array.

So no real hazards are happening. Because of the described behavior, when you combine slicing with multiple brackets basically the first one is already selecting part of the numpy array while the second bracket goes into the already selected array.

Explanation is available also here : numpy.org/devdocs/user/basics.indexing.html


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x