0

I have an array like this:

a = np.array(
    [[
        [
            [0.        , 0.        ],
            [0.        , 0.        ],
            [0.        , 0.        ]
        ],
        [
            [0.07939843, 0.13330124],
            [0.20078699, 0.17482429],
            [0.49948007, 0.52375553]
        ]
    ]]
)
a.shape
>>> (1, 2, 3, 2)

Now I need to compare the values in the last dimension and replace the maximum with 1 and the minimum with 0. So I need a result like this:

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

         [[0., 1.],
          [1., 0.],
          [0., 1.]]]])

Well, I have tried a nested loop like this:

for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        for k in range(a.shape[2]):
            if a[i, j, k, 0] > a[i, j, k, 1]:
                a[i, j, k, 0] = 1
                a[i, j, k, 1] = 0
            else:
                a[i, j, k, 0] = 0
                a[i, j, k, 1] = 1

However, I need a faster way, maybe a built-in function of NumPy library.

2
  • Check stackoverflow.com/questions/19666626/… Commented Aug 22, 2021 at 17:32
  • @Sujay I checked that. Thank you. But that seems to be useful when we want to compare the values with a constant value. How can I compare two values in the same dimension using the approach you suggested? Commented Aug 22, 2021 at 17:43

1 Answer 1

1

Manually construct the indices for 1 using argmax:

i, j, k, _ = a.shape
idx = np.ogrid[:i,:j,:k] + [a.argmax(-1)]
a[:] = 0
a[tuple(idx)] = 1

a
array([[[[1., 0.],
         [1., 0.],
         [1., 0.]],

        [[0., 1.],
         [1., 0.],
         [0., 1.]]]])
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.