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()
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.