简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM