Issue
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
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
Answered By - flawr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.