[英]Transform 3D numpy array in boolean 2D numpy array with nonzero condition
假設我們有以下 3D 數組:
[[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[1, 2, 1],
[0, 0, 0],
[4, 2, 1]],
[[0, 0, 0],
[1, 1, 3],
[0, 0, 0]]]
每當axis = 2中的每個元素分別不同或等於[0,0,0]時,我想減少數組的維度並獲得True或False。
上一個示例陣列所需的二維 output:
[[False, False, False]
[True, False, True],
[False, True, False]]
我們從 3x3x3 int/float 數組傳遞到 3x3 boolean 數組。
嘗試:
print(arr[:, :, 1] != 0) # 1 means second column, change to 0 for first, 2 for third column
印刷:
[[False False False]
[ True False True]
[False True False]]
注意:我使用了基於ndarray 的 numpy 索引。 [:,:, 1]
表示我想要來自每個二維矩陣、每一行和第二 (1) 列的值。 然后將這些值與0
進行比較,得到 boolean 矩陣。
IIUC 您想將最后一個維度與 [0,0,0] 進行比較,如果所有值都不同,則返回 False,否則返回 True。
假設a
陣列:
out = (a != [0,0,0]).any(2)
選擇:
out = ~(a == [0,0,0]).all(2)
Output:
array([[False, False, False],
[ True, False, True],
[False, True, False]])
>>> test = [[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[1, 2, 1],
[0, 0, 0],
[4, 2, 1]],
[[0, 0, 0],
[1, 1, 3],
[0, 0, 0]]]
>>> [[not ee == [0, 0, 0] for ee in e] for e in test]
import numpy as np
arr = np.array([
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
],
[
[1, 2, 1],
[0, 0, 0],
[4, 2, 1],
],
[
[0, 0, 0],
[1, 1, 3],
[0, 0, 0],
]
])
answer = (arr != 0).any(axis=2)
print(answer)
# [[False False False]
# [ True False True]
# [False True False]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.