python - 获取numpy数组中特定值的索引

标签 python numpy

我知道了。 numpy 数组:

arr = [0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1]

这就是我如何获取数组中所有 0 的索引:

inds = []
for index,item in enumerate(arr):     
    if item == 0:
        inds.append(index)

是否有一个 numpy 函数可以做同样的事情?

最佳答案

你可以使用 numpy.argwhere正如@chappers 在评论中指出的那样:

arr = np.array([0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1])

In [34]: np.argwhere(arr == 0).flatten()
Out[34]:
array([ 0,  1,  2,  4,  5,  6,  7,  8,  9, 10, 12, 14, 16, 17, 18, 19, 20,
       21, 22, 23, 24, 25], dtype=int32)

或者使用 astype(bool) 的逆函数:

In [63]: (~arr.astype(bool)).nonzero()[0]
Out[63]:
array([ 0,  1,  2,  4,  5,  6,  7,  8,  9, 10, 12, 14, 16, 17, 18, 19, 20,
       21, 22, 23, 24, 25], dtype=int32)

关于python - 获取numpy数组中特定值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34126230/

相关文章:

python - 将 str 分数转换为 pandas df 中的 float

python - DataFrame 'groupby' 正在修复带有索引的组列

python - 当小数>=1时,pandas/numpy round()如何工作?

python - 使用 matplotlib 设置 plt.axis ('off' )时出错

python - 如何矢量化 3D numpy 数组中切片的阈值

python - Django:如何检查用户是否已经在ManyToManyField上投票?

python - 如何在 python 正则表达式中实现\p{L}

python - sklearn DictVectorizer(sparse=False) 具有不同的默认值,估算一个常数

numpy - xt::where 用于 xtensor C++ 的示例用法

python - numpy 中的 3d 矩阵乘法