I want to set the max value in a numpy array equal to 1, and the rest of the values to 0, so that there is only one value equal to 1 in the new array.
Right now I'm doing this with:
new_arr = np.where(arr == np.max(arr), 1, 0)
However, if there are multiple values in arr that are equal to np.max(arr) then there will be multiple values in new_arr equal to 1.
How do I make it so that there is only one value in new_arr equal to 1 (the first value equal to np.max(arr) seems like a fine option but not necessary).
You can use:
new_arr = np.zeros(shape=arr.shape)
new_arr[np.unravel_index(np.argmax(arr),shape=arr.shape)] = 1
This also works for multi-dimensional arrays. np.argmax gives the flattened index of the first instance of the max element, and np.unravel_index converts the flat index to the index based on the array shape.
You almost have it.
This will give you the index of the last occurrence of the max value
np.where(arr == np.max(arr))[0][-1]
and if you want the first occurence of the maximum value, it is :
np.where(arr == np.max(arr))[0][0]
Example
import numpy as np
arr = np.array(np.random.choice([1, 2, 3, 4], size=10))
print(arr)
Output : [4 1 2 4 1 1 4 2 4 3]
Then:
np.where(arr == np.max(arr))[0][-1] # last index of max value
Output: 8
or
np.where(arr == np.max(arr))[0][0] # first index of max value
Output: 0
You can then proceed to replace by index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With