Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearranging Matrix Elements with Numpy

I have a NumPy matrix which I've simplified to exemplify:

       a  b  c  d  e  f 
A =  [[0, 1, 2, 3, 4, 5],
 b    [1, 0, 3, 4, 5, 6],
 c    [2, 3, 0, 5, 6, 7],
 d    [3, 4, 5, 0, 7, 8],
 e    [4, 5, 6, 7, 0, 9],
 f    [5, 6, 7, 8, 9, 0]]

where the number at the "intersections" is important, but their order is not right. I want to re-arrange the rows and columns such that the new order is [a, d, b, e, c, f] but this value that I'm calling "the intersection" is the same.

Below I have started to transform the matrix how I want. Filling the 'e' row involves looking at the intersections above for (e,a) (= 4), then (e,d) (=7) , then (e,b) (=5), (e,e), (e,c), and (e,f)

       a  d  b  e  c  f
A1=  [[0, 3, 1, 4, 2, 5],
 d    [3, 0, 4, 7, 5, 8],
 b    [1, 4, 0, 5, 3, 6],  
 e    [4, 7, 5, 

Can anyone please suggest how to re-arrange my matrix in this manner?

like image 208
emmagras Avatar asked Jun 07 '12 17:06

emmagras


1 Answers

Numpy provides many methods to manipulate arrays, including rolling elements along an xis, rolling all axes, swap axes. You can use a combination of these to get the desired order of elements

like image 52
Dhara Avatar answered Oct 14 '22 04:10

Dhara