今天发现ndarray能实现算数运算,但不能实现逻辑运算
如果想掩盖掉>=3且<=6的部分,如下逻辑运算是会报错的:a >= 3 and a <= 6
a = np.array([1, 2, 3, 4, 5, 6, 7])
print(a >= 3 and a <= 6)
---
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
解决方法:用算数运算代替逻辑运算,即(a >= 3) * (a <= 6)
print(f"a >= 3 : {a >= 3}")
print(f"a <= 6 : {a <= 6}")
print(f"a >= 3 and a <= 6: {(a >= 3) * (a <= 6)}")
print(f"range = {(a >= 3) * (a <= 6) * a}")
输出结果:
a >= 3 : [False False True True True True True]
a <= 6 : [ True True True True True True False]
a >= 3 and a <= 6: [False False True True True True False]
range = [0 0 3 4 5 6 0]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)