'How to replace min and max value row in 2-d array python
i have an 2-d array(matrix) 3x3 like [[1, 2, 3],[4, 5, 6],[7, 8, 9]] and i need to replace 2 rows where is max and min value so its looks like: [[7, 8, 9],[4, 5, 6],[1, 2, 3]]
from random import randint
def array():
column = int(input())
row = int(input())
arr = [[randint(1, 100) for i in range(column)] for y in range(row)]
print(arr)
array()
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
a = np.random.randint(0, 999, size=(10,10))
# find the row indices of min and max
imin = np.argmin(np.min(a,axis=1))
imax = np.argmax(np.max(a,axis=1))
# swap the rows
a[[imin,imax]] = a[[imax,imin]]
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 |