np.where多个筛选条件

a = 0,1,2,3,4,5

想要筛选出"大于等于2并且小于等于4"的数字下标,首先尝试了如下写法

python 复制代码
import numpy as np
a = np.arange(6)
print(np.where(a>=2 & a<=4))

程序会报错

bash 复制代码
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2023.2.3\plugins\python-ce\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

正确写法是

python 复制代码
import numpy as np
a = np.arange(6)
print(np.where((a>=2) & (a<=4)))

给每个条件加上括号即可。

还有另外一种写法,使用np.logical_and来实现。

python 复制代码
import numpy as np
a = np.arange(6)
print(np.where(np.logical_and(a>=2, a<=4)))
相关推荐
广州景颐光电3 天前
3种NumPy向量化实测:光源数据处理从2.3秒压到12.3ms
numpy
梅雅达编程笔记5 天前
零基础学 Python 第14章 | 模块、包与第三方库
开发语言·python·django·numpy·pandas
梅雅达编程笔记5 天前
零基础学 Python 第15章 | 类与对象:面向对象编程入门
开发语言·python·django·numpy·pandas
pulinzt5 天前
Tableau的基础使用
数据库·numpy
梅雅达编程笔记6 天前
编程启蒙|Scratch 转 Python 系列第9天:字典/哈希表积木双向对照(AI大模型参数配置表实战)
开发语言·人工智能·python·numpy·pandas
汤姆小白8 天前
08-应用部署
人工智能·python·机器学习·numpy·transformer
汤姆小白9 天前
02-Tokenizer原理与实现
人工智能·python·机器学习·numpy
汤姆小白9 天前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
CS创新实验室10 天前
NumPy数组的C风格和Fortran风格
c语言·开发语言·numpy
梅雅达编程笔记10 天前
零基础学 Python 第7章 | 字典 dict:键值对存储
开发语言·python·beautifulsoup·numpy·pandas