0

I'm trying to understand some code and I've encountered a negative index in a 3d array and I'm confused.

First a toy example:

import numpy as np
mis = np.random.rand(2, 3, 4)

np.sort(mis, axis=2)[:, :, -2]
Out[428]: 
array([[0.409, 0.406, 0.668],
       [0.806, 0.715, 0.442]])

Ok. so playing around with this toy example I changed -2 to +2:

np.sort(mis, axis=2)[:, :, 2]
Out[429]: 
array([[0.409, 0.406, 0.668],
       [0.806, 0.715, 0.442]])

Whats going on here, why is the answer the same ? In my real data the size of mis in all 3 dimensions could be much larger so I want to understand this properly. Thanks!

Edit: Note I've tried the toy with mis having dimension (2,3,20) and the results are not the same from that - but this just confuses me more!

2 Answers 2

1

It returns the same result because -2 represents the second element starting from the end, and 2 represents the 3rd element starting from the beginning (the first element is indexed to zero). Therefore it returns always the third element of the array.

In the examples below I put between asteriscs the elements involved.

[[[0.22370153 0.26788364 **0.29264144** 0.83075949]
  [0.16376808 0.25345179 **0.26835547** 0.62549444]
  [0.37718569 0.61648076 **0.65733173** 0.68745722]]

[[0.1519311  0.44252181 **0.67729233** 0.83835924]
  [0.11297116 0.11889391 **0.26749958** 0.98031619]
  [0.03599794 0.35117534 **0.88740645** 0.93831347]]]
Sign up to request clarification or add additional context in comments.

Comments

1

In this problem your third dimension is of size 4 with indexes [0,1,2,3] and you have choosen -2 index which means 2nd from last which is basically your 3rd index from starting which is 2 that is why both are same

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.