python - 我如何获得包含一个的numpy数组的索引

标签 python numpy numpy-ndarray indices

如何优雅地获取 numpy 数组中包含 1 的元素的索引?

我试着做一个循环:

indexes = []
for i in range(len(array)):
    if array[i] == 1:
    indexes += [i]

最佳答案

使用np.where:

a = np.array([0, 0, 1, 1, 0, 1, 1, 1, 0])
np.where(a)

输出:

(array([2, 3, 5, 6, 7], dtype=int64),)

或者np.nonzero:

a.nonzero()

输出:

(array([2, 3, 5, 6, 7], dtype=int64),)

你也可以索引到np.arange:

np.arange(len(a))[a.astype(bool)]

输出:

array([2, 3, 5, 6, 7])

关于python - 我如何获得包含一个的numpy数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870144/

相关文章:

python - 将 numpy ndarray 数组元素展平为特征行

python - 寻找使用 numpy 根据出现次数对 3d 数组进行下采样的最快方法

python - 匀称的线串 .length 单位

python - df.columns 返回 RangeIndex

python - 为什么 B = numpy.dot(A,x) 循环执行 B[i, :, :] = numpy. dot(A[i, :, :], x) ) 如此慢?

python - 通过 if 条件在二维数组之间进行元素明智的比较

python - 检查 numpy 数组是否全部非负的最佳方法

python - Matplotlib Agg 渲染复杂度错误

java - NumberFormatException 的含义是什么以及如何解决它?

列表的 Python 列表与 numpy