2

I'm a beginner to the Python world and hope someone can answer my question. I haven an array and need to access certain indices of elements as below

x = np.random.rand(10)

x
array([ 0.56807058,  0.8404783 ,  0.86835717,  0.76030882,  0.40242679,
        0.22941009,  0.56842643,  0.94541468,  0.92813747,  0.95980955])

indx = np.where(x < 0.5)

indx
(array([4, 5], dtype=int64),)

However, when I try to access first element with indx[0] it returns array([4, 5], dtype=int64). What I want to do is access elements 4 and 5 inside indx. Thank you for looking into my question and any support.

1
  • if indx[0] gets array([4, 5], what do you think will get 4? Commented Jul 2, 2015 at 23:28

1 Answer 1

2

np.where returns a tuple of indices. In this case the tuple contains only one array of indices. This consistent with how where handles multi-dimensional arrays. It returns a tuple containing multiple arrays which together define the indices of the non-zero elements.

To access 4 from indx you would do: indx[0][0]. The first [0] selects the first element of the indx tuple, which is array([4, 5], dtype=int64) and the second accesses an element of this array.

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.