gpt4 book ai didi

从 bool 数组设置 Python numpy 索引

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:48 25 4
gpt4 key购买 nike

如何将 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,它基本上等同于问题中的长格式。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com