在Python中获取数组的索引

raj*_*123 0 python numpy list python-3.x

我有一个A包含True, False元素的 numpy 数组。我想打印所有包含False元素的索引。但是,我收到错误。我提出预期的输出:

import numpy as np

A=np.array([[False],
       [False],
       [ True],
       [False],
       [False]])

for i in range(0,len(A)):
    if (A[i]==['False']): 
        print(i)
Run Code Online (Sandbox Code Playgroud)

错误是:

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if (A[i]==['False']):
Run Code Online (Sandbox Code Playgroud)

预期输出是:

[0,1,3,4]
Run Code Online (Sandbox Code Playgroud)

Ala*_* T. 6

您可以使用 argwhere 一次性获取这些索引:

indices = np.argwhere(A==False)[:,0]  # extract only row indexes from output

print(indices)
# [0 1 3 4]
Run Code Online (Sandbox Code Playgroud)

使用 np.where 进行解包也可以工作:

indices,_ = np.where(A==False)

print(indices)
# [0 1 3 4]
Run Code Online (Sandbox Code Playgroud)