Home > Software design >  Matrix sorting in specific order in Python
Matrix sorting in specific order in Python

Time:05-04

I have a 171x5 matrix, in which the second column contains numbers in the order from 0 to 170 and three values ​​corresponding to each such number. And in the first column are the values in the desired order. And I want to sort the matrix in the order presented in the first column.

#A

[[ 15  0  1.124  8.822 1.010]
 [ 10  1  8.228 -9.960 2.537]
...
 [ 25  170  9.495 -1.187 -6.590]]

The output should be:

#B
[[ 15  15  4.185  8.822 9.895]
 [ 10  10  7.225 -7.929 8.589]
...
 [ 25  25  2.455 -5.145 -7.597]]

CodePudding user response:

Let's say you have matrix A that you want to sort by its first column.

You can use a standard Python function for sorting and pass a key argument that defines the order of sorting.

The lambda function passed as an argument would be selecting first element from each row as the key and the key would be used for the sorting order

sorted(A, key = lambda x: x[0])
  • Related