簡體   English   中英

Boolean 索引 numpy 帶有或邏輯運算符的數組

[英]Boolean Indexing numpy Array with or logical operator

我試圖在 Numpy 數組上做一個or boolean 邏輯索引,但我找不到一個好方法。 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)

Output:

[[ 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_andnumpy.logical_xornumpy.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

這不是一個非常pythonic的答案。 但是很清楚

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM