1

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.

0

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

10 Comments

It did not work :(
@Janikas Can you explain more? What did not work?
Sorry, my bad! It worked! :)
It would be nice if you explain how this works. To the best of my knowledge arr[:, :, 1] just takes the element at position 1 for each array at axis 2
@DaniMesejo Yes, I added short explanation.
|
2

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]])

2 Comments

(test != [0,0,0]).all(2) should also work. I believe the notion of each element different needs to be addressed by all rather than any
@onyambu yes could be, the example is unfortunately ambiguous (all zero or all non-zero)
1
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]]

Comments

0
 >>> 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]

1 Comment

I used list instead of numpy array. You can convert the numpy array to list first by "test.tolist()"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.