How to replace element in NumPy array?

My goal is to find the maximum value of the array and replace it with a number. To achieve this, I wrote a code below but it’s not working.

vec = np.random.randint(0, 100, size=10)
print('Array: ',vec)
# Find the index of the maximum value
max_index = np.where(vec == max(vec))
# Replace the maximum value by 0
max_index[vec] = 0
print('Final_Array: ',vec)

TypeError: only integer scalar arrays can be converted to a scalar index

Can you correct the code or provide me with different methods that replace elements of the array?

Certainly @safa, here is a method that can solve your problem:

  • This code creates a NumPy array of size 10, with random float values between 0 and 1.
  • After which it uses the argsort() function to find the index of the maximum value in the array. This function sorts the array in ascending order and returns the indices of the sorted elements.
  • It then replaces the maximum value (the last element of the sorted array) with 0 using the index found.