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)))
相关推荐
对方正在长头发丿10 小时前
Numpy学习篇
python·学习·jupyter·pycharm·numpy
狮子雨恋11 小时前
Python 多维数组学习示例
python·学习·numpy
laocooon5238578862 天前
对传入的 x , y 两个数组做折线图, x 对应 x 轴, y 对应 y 轴。并保存到 Task1/image1/T2.png
python·numpy·pandas·matplotlib
中科院提名者3 天前
KNN实战进阶:模型评估、Scikit-learn实现与Numpy手动编码
python·numpy·scikit-learn
Maxwell_li13 天前
新冠检测例子学习查准率和召回率
学习·机器学习·数据分析·回归·numpy·pandas
渡我白衣3 天前
Python 与数据科学工具链入门:NumPy、Pandas、Matplotlib 快速上手
人工智能·python·机器学习·自然语言处理·numpy·pandas·matplotlib
Amber_374 天前
数据分析之(MySQL+普通程序) VS (Python的NumPy/Pandas)
python·mysql·数据分析·numpy·pandas
癫狂的兔子8 天前
【Python】【NumPy】学习笔记
python·学习·numpy
MarkHD8 天前
智能体在车联网中的应用:第12天 Python科学计算双雄:掌握NumPy与Pandas,筑牢AI与自动驾驶数据基石
人工智能·python·numpy
Lucky高10 天前
NumPy库实践5_输入和输出
numpy