Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swap min and max value in NumPy array

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading