How do I binarize a numpy array to indicate the max value of each row?

Viewed 93

If I have a numpy array, how do I convert so that the value of each element is zero, except for the max element of each row, which should be 1, without a brute-force looping solution? For example, given:

array([[1, 2, 3, 4],
       [2, 3, 4, 1],
       [3, 4, 1, 2],
       [4, 1, 2, 3]])

How do I produce:

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

Note: For my actual case, I won't know the actual values in the array. All I will know is that the values are non-negative.

2 Answers

Try the following code:

import numpy as np
ar = np.array([[1, 2, 3, 4],
               [2, 3, 4, 1],
               [3, 4, 1, 2],
               [4, 1, 2, 3]])
ar = (ar == ar.max()) * 1
print(ar)

You can use .max(), and then convert the resulting boolean matrix into a binary matrix using .astype():

import numpy as np

arr = np.array([[1, 2, 3, 4],
[2, 3, 4, 1],
[3, 4, 1, 2],
[4, 1, 2, 3]])

result = (arr == arr.max()).astype(int)

print(result)
Related