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

Locate the largest element and swap with the first in Python

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]]

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

>Solution :

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]])
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