我知道Python列表有一个方法可以返回某个对象的第一个索引:

>>> xs = [1, 2, 3]
>>> xs.index(2)
1

NumPy数组也有类似的东西吗?


当前回答

是的,给定一个数组,数组和一个值,要搜索的项,你可以使用np。的地方:

itemindex = numpy.where(array == item)

结果是一个元组,首先是所有的行索引,然后是所有的列索引。

例如,如果一个数组是二维的,它包含你的项目在两个位置,那么

array[itemindex[0][0]][itemindex[1][0]]

将等于你的项目,因此将是:

array[itemindex[0][1]][itemindex[1][1]]

其他回答

找到了另一个循环解决方案:

new_array_of_indicies = []

for i in range(len(some_array)):
  if some_array[i] == some_value:
    new_array_of_indicies.append(i)
    

是的,给定一个数组,数组和一个值,要搜索的项,你可以使用np。的地方:

itemindex = numpy.where(array == item)

结果是一个元组,首先是所有的行索引,然后是所有的列索引。

例如,如果一个数组是二维的,它包含你的项目在两个位置,那么

array[itemindex[0][0]][itemindex[1][0]]

将等于你的项目,因此将是:

array[itemindex[0][1]][itemindex[1][1]]

对于1D数组,我推荐np。平坦非零(array == value)[0],它等价于np。非零(array == value)[0][0]和np。其中(array == value)[0][0],但避免了对一个单元素元组开箱的丑陋。

如果你想用它作为其他东西的索引,如果数组是可广播的,你可以使用布尔索引;不需要显式索引。要做到这一点,绝对最简单的方法是基于真值进行索引。

other_array[first_array == item]

任何布尔运算都可以:

a = numpy.arange(100)
other_array[first_array > 50]

非零方法也接受布尔值:

index = numpy.nonzero(first_array == item)[0][0]

两个0分别表示索引元组(假设first_array是1D)和索引数组中的第一项。

index_lst_form_numpy = pd.DataFrame(df).reset_index()["index"].tolist()