我试图在 Numpy 数组上进行or
布尔逻辑索引,但我找不到好方法。and operator &
正常工作,如下所示:
X = np.arange(25).reshape(5, 5)
# We print X
print()
print('Original X = n', X)
print()
X[(X > 10) & (X < 17)] = -1
# We print X
print()
print('X = n', X)
print()
Original X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 -1 -1 -1 -1]
[-1 -1 17 18 19]
[20 21 22 23 24]]
但是当我尝试:
X = np.arange(25).reshape(5, 5)
# We use Boolean indexing to assign the elements that are between 10 and 17 the value of -1
X[ (X < 10) or (X > 20) ] = 0 # No or condition possible!?!
我收到错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
是否存在使用 or 逻辑运算符的好方法?
您可以通过以下方式将numpy.logical_or
用于该任务:
import numpy as np
X = np.arange(25).reshape(5,5)
X[np.logical_or(X<10,X>20)] = 0
print(X)
输出:
[[ 0 0 0 0 0]
[ 0 0 0 0 0]
[10 11 12 13 14]
[15 16 17 18 19]
[20 0 0 0 0]]
还有numpy.logical_and
、numpy.logical_xor
和numpy.logical_not
我会用np.logical_and和np.where的东西。 对于您给出的示例,我相信这会起作用。
X = np.arange(25).reshape(5, 5)
i = np.where(np.logical_and(X > 10 , X < 17))
X[i] = -1
这不是一个非常蟒蛇的答案。但很清楚