Home > Back-end >  Swap the rows that contain the minimum and maximum elements of the matrix Python
Swap the rows that contain the minimum and maximum elements of the matrix Python

Time:04-09

I need to create matrix

matrix = np.random.randint(1, 100, size = (3, 3), dtype='l')

and it`s looks likee

10 45 74
59 20 15
86 41 76

and i need to swap rows that contains max and min number like that

86 41 76
59 20 15
10 45 74

how i can do it?

CodePudding user response:

Here is one (boring) solution:

import numpy as np

mat = np.array([
  [10, 45, 74],
  [59, 20, 15],
  [86, 41, 76],
])

max_row_id = mat.max(1).argmax()  # row index with maximum element
min_row_id = mat.min(1).argmin()  # row index with minimum element
row_idx = np.arange(mat.shape[0]) # index of row ids
row_idx[max_row_id] = min_row_id  # swap row ids for rows with min and max elements
row_idx[min_row_id] = max_row_id

result = mat[row_idx,:]

CodePudding user response:

I think using np.unravel_index be one of the fastest way besides the following advanced indexing to swap the rows:

row_min = np.unravel_index(np.argmin(mat), mat.shape)[0]
row_max = np.unravel_index(np.argmax(mat), mat.shape)[0]
mat[[row_min, row_max]] = mat[[row_max, row_min]]

Benchmarks (Colab):

# matrix (3*3)                           FASTEST
1000 loops, best of 5: 8.7 µs per loop   ------> hilberts_drinking_problem method
1000 loops, best of 5: 14.3 µs per loop

#  matrix (1000*3)  
100 loops, best of 5: 65   µs per loop
100 loops, best of 5: 21.9 µs per loop   ------> This method 

# matrix (1000*1000)
100 loops, best of 5: 3.44 ms per loop
100 loops, best of 5: 2.64 ms per loop   ------> This method

# matrix (10000*10000)
10 loops, best of 5: 388 ms per loop
10 loops, best of 5: 282 ms per loop     ------> This method
  • Related