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]] 
2
  • You can find the answer to your question here: stackoverflow.com/questions/45648668/… Commented Mar 17, 2021 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. Commented Mar 17, 2021 at 19:05

4 Answers 4

3

Not sure if most pythonic, but you can do:

(test_array == max(test_array)) * 1 
Sign up to request clarification or add additional context in comments.

1 Comment

very pythonic! Thank you
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).

Comments

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

Comments

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.