0

我试图对orNumpy 数组进行布尔逻辑索引,但我找不到一个好方法。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 逻辑运算符的好方法?

4

2 回答 2

0

您可以通过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_xornumpy.logical_not

于 2020-05-13T08:10:44.213 回答
0

我会在 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

这不是一个非常pythonic的答案。但是很清楚

于 2020-05-13T08:13:00.033 回答