Home > Software design >  Transform 3D numpy array in boolean 2D numpy array with nonzero condition
Transform 3D numpy array in boolean 2D numpy array with nonzero condition

Time:07-27

Imagine we have the following 3D 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]]]

I want to reduce the dimension of the array and obtain True or False whenever each element in axis=2 is different or equal to [0, 0, 0], respectively.

Desired 2D output for the previous example array:

[[False, False, False]
 [True, False, True],
 [False, True, False]]

We pass from 3x3x3 int/float array to a 3x3 boolean array.

CodePudding user response:

Try:

print(arr[:, :, 1] != 0)  # 1 means second column, change to 0 for first, 2 for third column

Prints:

[[False False False]
 [ True False  True]
 [False  True False]]

Note: I used basing numpy indexing of ndarray. [:, :, 1] means that I want values from every 2D matrix, every row and second (1) column. Then compare these values to 0 to obtain boolean matrix.

CodePudding user response:

IIUC you want to compare the last dimension to [0,0,0], returning False if all values are different, True otherwise.

Assuming a the 3D array:

out = (a != [0,0,0]).any(2)

Alternative:

out = ~(a == [0,0,0]).all(2)

Output:

array([[False, False, False],
       [ True, False,  True],
       [False,  True, False]])

CodePudding user response:

 >>> 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]
  • Related