unaied
unaied

Reputation: 307

pythonic way to convert values in a numpy array to either 0 or 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]]

Upvotes: 1

Views: 462

Answers (4)

kennyvh
kennyvh

Reputation: 2854

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)

Upvotes: 1

itwasthekix
itwasthekix

Reputation: 615

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]])

Upvotes: 1

Paul Daly
Paul Daly

Reputation: 26

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).

Upvotes: 1

Yilun Zhang
Yilun Zhang

Reputation: 9008

Not sure if most pythonic, but you can do:

(test_array == max(test_array)) * 1

Upvotes: 3

Related Questions