Home > Software design >  Locate the largest element and swap with the first in Python
Locate the largest element and swap with the first in Python

Time:07-06

I want to locate the largest element of r2 and swap it with the element at r2[0,0]. I present the expected output.

import numpy as np
r2 = np.array([[  1.00657843,  63.38075613, 312.87746691],
       [375.25164461, 500.        , 125.75493382],
       [437.6258223 , 250.50328922, 188.12911152]])
indices = np.where(r2 == r2.max())

The expected output is

array([[  500.,  63.38075613, 312.87746691],
       [375.25164461,  1.00657843, 125.75493382],
       [437.6258223 , 250.50328922, 188.12911152]]

CodePudding user response:

You can store the maximum value in a variable, and then assign the [0, 0] element to the indices which you found with where and then set the [0, 0] element to the stored maximum value:

maximum = r2.max()
indices = np.where(r2 == maximum)
r2[indices] = r2[0, 0]
r2[0, 0] = maximum
r2

Output:

array([[500.        ,  63.38075613, 312.87746691],
       [375.25164461,   1.00657843, 125.75493382],
       [437.6258223 , 250.50328922, 188.12911152]])

CodePudding user response:

In this way you will replace all the element that have the max value

#get the max value of the array
max_value = np.max(r2)
#all the element with the max value will be replaced with the first value
r2[r2 == max_value] = r2[0][0]
#put the max value in the first position
r2[0][0] = max_value

CodePudding user response:

You could just return the index of the largest value and then swap with first index

# get index of largest value. 
index = np.unravel_index(r2.argmax(), r2.shape)
# swap with item at index 0,0
r2[index], r2[0,0] = r2[0,0], r2[index]
  • Related