2

I would like to replace values in a numpy array using boolean logic in dimensions >= 3. All the examples I can find are for 1d or 2d arrays such that you can say something like A[A>.5] = 1.
That I understand. I want to do something like this:

A[B==0,2 > 128] = 0. Basically, I have a 2D map (B) whose dimensions are the same as the first two in A. So everywhere B == 0 and the third channel (like B of RGB in an image) is greater than 128 I want to set the 3rd channel to zero, leaving the other two channels.

I can do this in a loop or doing a for value in array loop, but I was hoping someone could tell me if I could do it in a similar manner to A[A>.5] = 1.

I have tried A[B==0,2 > 128] = 0, but I get IndexError: in the future, 0-d boolean arrays will be interpreted as a valid boolean index and I can't really think of any other ways to write this.

One thing I forgot to mention - currently I can do A[B==0,2] = 0. I am just trying how to fit that extra conditional in.

1 Answer 1

2
A[(B == 0)*(A[..., 2] > 128), 2] = 0

Explanation:

  • B == 0 and A[..., 2] > 128 are the same dimensions, where [..., 2] specifies that slicing occurs in all axes in all dimensions until the last dimension, where only the axis indexed by 2 is sliced. This product of the two is False for any condition which doesn't fulfils your requirements.
  • 2 is the third axis of A on the last dimension.
Sign up to request clarification or add additional context in comments.

Comments

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.