?a = [0,1,2,3,4,5]
想要筛选出“大于等于2并且小于等于4”的数字下标,首先尝试了如下写法
import numpy as np
a = np.arange(6)
print(np.where(a>=2 & a<=4))
程序会报错
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()
正确写法是
import numpy as np
a = np.arange(6)
print(np.where((a>=2) & (a<=4)))
?给每个条件加上括号即可。
还有另外一种写法,使用np.logical_and来实现。
import numpy as np
a = np.arange(6)
print(np.where(np.logical_and(a>=2, a<=4)))