'Swapping individual lines of two dimensional arrays

so I have a question in school I've been trying to solve for a while now, but I just can't figure it out how do do it right. So the task at hand hand is to swap the array lines with the smallest and biggest integer in python, but I just can't figure it out. I know how to find the biggest and smallest integers in the arrays, but have no clue how to swap them. So if I have for example:

array1 = 
[[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[97, 98, 99, 100]]

how do i make it:

array1 =
[[97, 98, 99, 100]
[5, 6, 7, 8]
[9, 10, 11, 12]
[1, 2, 3, 4]]

Any input or idea how to solve it on my own is very much appreciated!



Solution 1:[1]

Using numpy, apply min and max to find smallest and largest number, then specify their locations with argmin, argmax. Finally swap the rows.

import numpy as np

array1 = np.array([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [97, 98, 99, 100]])

# find the row indices of min and max
imin = np.argmin(np.min(array1,axis=1)) 
imax = np.argmax(np.max(array1,axis=1)) 

# swap the rows
array1[[imin,imax]] = array1[[imax,imin]]

Output:

[[ 97  98  99 100]
 [  5   6   7   8]
 [  9  10  11  12]
 [  1   2   3   4]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AboAmmar