duliya
duliya

Reputation: 23

Access elements inside numpy.where index

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.

Upvotes: 2

Views: 1891

Answers (1)

YXD
YXD

Reputation: 32521

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.

Upvotes: 2

Related Questions