[英]Is there a way to NOT an arbitrary M x N matrix using numpy broadcasting?
我有多個0和1的矩陣,我想找到NOT的版本。 例如:
M
0 1 0
1 0 1
0 1 0
會成為:
!M
1 0 1
0 1 0
1 0 1
現在我有了
for row in image:
map(lambda x: 1 if x == 0 else 0, row)
哪個效果很好,但我有一種感覺,我已經看到這完成了簡單的廣播。 不幸的是,我沒有看到任何東西已經敲響了鍾聲。 我假設類似的操作將用於對矩陣的值進行閾值處理(即, 1 if x > .5 else 0
)。
給定0和1的整數數組:
M = np.random.random_integers(0,1,(5,5))
print(M)
# [[1 0 0 1 1]
# [0 0 1 1 0]
# [0 1 1 0 1]
# [1 1 1 0 1]
# [0 1 1 0 0]]
以下是您NOT
使用數組的三種方法:
轉換為布爾數組並使用~
運算符按位而NOT
數組:
print((~(M.astype(np.bool))).astype(M.dtype)) # [[0 1 1 0 0] # [1 1 0 0 1] # [1 0 0 1 0] # [0 0 0 1 0] # [1 0 0 1 1]]
使用numpy.logical_not
並將生成的布爾數組numpy.logical_not
為整數:
print(np.logical_not(M).astype(M.dtype)) # [[0 1 1 0 0] # [1 1 0 0 1] # [1 0 0 1 0] # [0 0 0 1 0] # [1 0 0 1 1]]
只需從1中減去所有整數:
print(1 - M) # [[0 1 1 0 0] # [1 1 0 0 1] # [1 0 0 1 0] # [0 0 0 1 0] # [1 0 0 1 1]]
對於大多數非布爾dtypes,第三種方式可能是最快的。
一種解決方案是將數組轉換為布爾數組
data = np.ones((4, 4))
bdata = np.array(data, dtype=bool)
print ~bdata
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.