1

I have a numpy array (10,1). I would like to replace the values inside this array with either 1 for the cell with the highest value or 0 for all other items. What the easiest pythonic way to do this please

test_array= [[0.24330683]
 [0.40597628]
 [0.33086422]
 [0.19425666]
 [0.32084166]
 [0.30551688]
 [0.14800594]
 [0.18241316]
 [0.14760117]
 [0.31546239]]
unaied
  • 197
  • 11
  • You can find the answer to your question here: https://stackoverflow.com/questions/45648668/convert-numpy-array-to-0-or-1 – TomM Mar 17 '21 at 19:02
  • Thanks Tom. I did actually look at that post but that was limited to converting any value that met a certain threshold I.e. >0.5. – unaied Mar 17 '21 at 19:05

4 Answers4

3

Not sure if most pythonic, but you can do:

(test_array == max(test_array)) * 1
TYZ
  • 8,466
  • 5
  • 29
  • 60
1

I think something like the below would work.

test_array_ranking = []
For num in test_array:
    if num == max(test_array):
        test_array_ranking.append(1)
    else:
        test_array_ranking.append(0)
print(test_array_ranking)

I haven't had a chance to test this exact coding but this is the path I would take (apologies that my post doesn't make the coding syntax clear).

Paul Daly
  • 26
  • 4
1

I'm sure this has already been answered, but I am partial to numpy.

import numpy as np

array = np.random.rand(10, 1)
np.where(array == array.max(), 1, 0)

array

Out[42]: 
array([[0.01829926],
       [0.83402693],
       [0.13217168],
       [0.94578615],
       [0.42469676],
       [0.19958485],
       [0.90554855],
       [0.77232316],
       [0.97036552],
       [0.07528272]])

array after threshold:

Out[47]: 
array([[0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [0],
       [1],
       [0]])
itwasthekix
  • 585
  • 6
  • 11
1

This solution uses a mask to set the max to 1 and everything else to 0.

import numpy as np

arr = np.array(
    [
        [0.24330683],
        [0.40597628],
        [0.33086422],
        [0.19425666],
        [0.32084166],
        [0.30551688],
        [0.14800594],
        [0.18241316],
        [0.14760117],
        [0.31546239],
    ]
)

max_mask = (arr == arr.max())

arr[max_mask] = 1
arr[~max_mask] = 0

print(arr)

Output

[[0.]
 [1.]
 [0.]
 [0.]
 [0.]
 [0.]
 [0.]
 [0.]
 [0.]
 [0.]]

Edit: This can be made even simpler to be:

arr = (arr == arr.max()).astype(int)
kennyvh
  • 2,526
  • 1
  • 17
  • 26