简体   繁体   English

访问 numpy.where 索引中的元素

[英]Access elements inside numpy.where index

I'm a beginner to the Python world and hope someone can answer my question.我是 Python 世界的初学者,希望有人能回答我的问题。 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) .但是,当我尝试使用indx[0]访问第一个元素时,它返回array([4, 5], dtype=int64) What I want to do is access elements 4 and 5 inside indx .我想要做的是访问indx元素 4 和 5 。 Thank you for looking into my question and any support.感谢您研究我的问题和任何支持。

np.where returns a tuple of indices. np.where返回一个索引tuple In this case the tuple contains only one array of indices.在这种情况下,元组只包含一个索引数组。 This consistent with how where handles multi-dimensional arrays.这与where处理多维数组的方式一致。 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] .要从indx访问4 ,您可以这样做: 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.第一个[0]选择indx元组的第一个元素,即array([4, 5], dtype=int64) ,第二个访问该数组的一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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