Home > Back-end >  Swap min and max value in NumPy array
Swap min and max value in NumPy array

Time:09-28

Is there any way of swapping min and max value in my NumPy 2D array?

import numpy as np

n = int(input("How many arrays: "))
m = int(input("How many numbers: "))

rng = np.random.default_rng()

arr = rng.random((n, m))

print(arr)

CodePudding user response:

With following snippet you first determine the minimum and maximum value in your array arr, then you find the positions of all the maxima and minima (there might be more than one entry of the array containing e.g. the maximal value) and store them in the boolean arrays max_mask/min_mask, and finally you use these boolean arrays to index the original array and insert the new values.

max = arr.max()
min = arr.min()
max_mask = arr == max
min_mask = arr == min
arr[max_mask] = min
arr[min_mask] = max
  • Related