Skip to main content
 首页 » 编程设计

python之numpy.where 用于 2+ 个特定值

2025年05月04日18freeliver54

numpy.where 函数可以用于多个特定值吗?

我可以指定一个特定的值:

>>> x = numpy.arange(5) 
>>> numpy.where(x == 2)[0][0] 
2 

但我想做类似下面的事情。它当然会出错。

>>> numpy.where(x in [3,4])[0][0] 
[3,4] 

有没有一种方法可以在不遍历列表并组合结果数组的情况下做到这一点?

编辑: 我还有一个未知长度和未知值的列表列表,因此我无法轻易形成 np.where() 的参数来搜索多个项目。传递一个列表会容易得多。

请您参考如下方法:

您可以将 numpy.in1d 函数与 numpy.where 一起使用:

import numpy 
numpy.where(numpy.in1d(x, [2,3])) 
# (array([2, 3]),)