Skip to main content
 首页 » 编程设计

python之访问 numpy.where 索引中的元素

2024年10月24日12unruledboy

我是 Python 世界的初学者,希望有人能回答我的问题。我有一个数组,需要访问元素的某些索引,如下所示

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),) 

但是,当我尝试使用 indx[0] 访问第一个元素时,它返回 array([4, 5], dtype=int64)。我想要做的是访问 indx 中的元素 4 和 5。感谢您调查我的问题和任何支持。

请您参考如下方法:

np.where 返回索引的 tuple。在这种情况下,元组仅包含一个索引数组。这与 where 处理多维数组的方式一致。它返回一个包含多个数组的元组,这些数组共同定义了非零元素的索引。

要从 indx 访问 4,您可以这样做:indx[0][0]。第一个 [0] 选择 indx 元组的第一个元素,即 array([4, 5], dtype=int64) 和第二个访问该数组的一个元素。