0

I have a 3d array like this:

array([[[ 0,  1],
        [ 0,  0]],

        [[ 0,  0],
        [ 6,  7]]])

What I am trying to do is reduce it to a 2d array like this:

array([[1, 0],
       [0, 1]])

Where there is a 1 for each sub-array of the original that had non-zero elements, and a 0 if all the elements of the corresponding sub-array were zero.

How can I do this cleanly, without loops?

1 Answer 1

1

You can use numpy.ndarray.any along the last axis (axis=-1):

>>> arr = np.array([[[ 0,  1],
        [ 0,  0]],

        [[ 0,  0],
        [ 6,  7]]])

>>> arr.any(axis=-1).astype(int)
array([[1, 0],
       [0, 1]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.