Python numpy 从 bool 数组设置索引

标签 python numpy

如何将 bool 数组转换为可迭代的索引?

例如,

import numpy as np
import itertools as it
x = np.array([1,0,1,1,0,0])
y = x > 0
retval = [i for i, y_i in enumerate(y) if y_i] 

还有更好的方法吗?

最佳答案

尝试np.wherenp.nonzero .

x = np.array([1, 0, 1, 1, 0, 0])
np.where(x)[0] # returns a tuple hence the [0], see help(np.where)
# array([0, 2, 3])
x.nonzero()[0] # in this case, the same as above.

参见help(np.where)help(np.nonzero)

可能值得注意的是,在 np.where 页面中,它提到对于 1D x 它基本上相当于问题中的长格式。

关于Python numpy 从 bool 数组设置索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14681250/

相关文章:

Python:TypeError:Unicode 对象必须在散列之前编码

python - 尝试针对随机森林模型进行测试时,如何修复 “Number of features error”?

python - 如何使用 pandas 中的正则表达式来屏蔽具有某些 nan 值的列?

python - 如何在 Python 中索引 0-d 数组?

python - numpy where 最多接受 3 个参数 - 解决这个问题的方法?

python - Django 和 ManyToMany 字段

python - 如何删除数组中的 ' ' [ ] (python)

python - 如何使用networkx将边添加到列表末尾

python - 在 python/numpy 中随机放置给定数字的矩阵

python - 不使用 Intel MKL/BLAS/ATLAS/LAPACK 编译 numpy