Python 3.x 这个numpy.where()方法可以适应两种情况而不是一种情况吗?
我可以让Python 3.x 这个numpy.where()方法可以适应两种情况而不是一种情况吗?,python-3.x,numpy,indexing,multiple-conditions,Python 3.x,Numpy,Indexing,Multiple Conditions,我可以让numpy.where()在一个条件下工作,但不能在两个条件下工作 对于一种情况: import numpy as np a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5]) i, = np.where(a < 2) print(i) >> [ 0 5 8 10 11 12] ## indices where a[i] = 1 # condition = (a > 1 and a &l
numpy.where()
在一个条件下工作,但不能在两个条件下工作
对于一种情况:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5])
i, = np.where(a < 2)
print(i)
>> [ 0 5 8 10 11 12] ## indices where a[i] = 1
# condition = (a > 1 and a < 3)
# i, = np.where(condition)
i, = np.where(a > 1 and a < 3)
print(i)
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
将numpy导入为np
a=np.数组([1,2,3,4,5,1,2,3,1,2,1,1,1,2,4,5])
i、 =np.其中(a<2)
印刷品(一)
>>[0 5 8 10 11 12]##指数,其中a[i]=1
对于两种情况:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5])
i, = np.where(a < 2)
print(i)
>> [ 0 5 8 10 11 12] ## indices where a[i] = 1
# condition = (a > 1 and a < 3)
# i, = np.where(condition)
i, = np.where(a > 1 and a < 3)
print(i)
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
#条件=(a>1和a<3)
#i,=np.where(条件)
i、 =np.其中(a>1且a<3)
印刷品(一)
>>ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()
我阅读了a.any()
和a.all()
,但这不符合我的目的,因为我需要符合条件的所有索引,而不是一个布尔值
有没有一种方法可以将其适应于两种情况?使用
np。其中((a>1)和(a<3))
当您在标量上下文中使用布尔数组(如if
)或在本例中使用Python的和)时,会产生此值错误。改用和。并使用()
控制操作员命令。