Sorting a matrix arbitrarily by columns

Viewed 45

I have a matrix like:

[[col1,col2,col3,col4,col5],
 [4,1,3,6,2],
 [9,4,1,3,6]]

I want to reorder the matrix by columns arbitrarily like:

[[col3,col1,col5,col4,col2],
 [3,4,2,6,1],
 [1,9,6,3,4]]

I know that if that would be one row, I could create an order list like order_list = [2,0,4,3,1] and then use list comprehension ordered_list = [old_list[i] for i in order_list] but here I couldn't come up with a way to create a nested comprehension where I do this operation for each row.

2 Answers

I suggest using numpy's fancy indexing.

>>> import numpy as np
>>> a = np.array([[4,1,3,6,2], [9,4,1,3,6]])                                                                                           
>>> cols = [2,0,4,3,1]                                                                                                                 
>>> a.T[cols].T                                                                                                                        
>>> 
array([[3, 4, 2, 6, 1],
       [1, 9, 6, 3, 4]])

Details:

>>> a
array([[4, 1, 3, 6, 2],
       [9, 4, 1, 3, 6]])
>>> a.T
array([[4, 9],
       [1, 4],
       [3, 1],
       [6, 3],
       [2, 6]])
>>> a.T[cols]
array([[3, 1],
       [4, 9],
       [2, 6],
       [6, 3],
       [1, 4]])
>>> a.T[cols].T
array([[3, 4, 2, 6, 1],
       [1, 9, 6, 3, 4]])

If list comprehesion is what you must do.

Having a list

l=[[2,0,1],[4,5,6],[7,8,9]]

Using some list slicing you can do

>>> [[x[i] for i in l[0]] for x in l[1:]]
[[6, 4, 5], [9, 7, 8]]

If you want the whole array back you can do

>>> [l[0]]+[ [x[i] for i in l[0]] for x in l[1:]]
[[2, 0, 1], [6, 4, 5], [9, 7, 8]]
Related