katsuki94
katsuki94

Reputation: 3

How to do an absolute sorting of columns in a matrix (numpy)

So i have a matrix:

    a = np.array([[7,-1,0,5],
                  [2,5.2,4,2],
                  [3,-2,1,4]])

which i would like to sort by absolute value ascending column . I used np.sort(abs(a)) and sorted(a,key=abs), sorted is probably the right one but do not know how to use it for columns. I wish to get

    a = np.array([[2,-1,0,2],
                  [3,-2,1,4],
                  [7,5.2,4,5]])
                 

Upvotes: 0

Views: 155

Answers (1)

Henry Ecker
Henry Ecker

Reputation: 35686

Try argsort on axis=0 then take_along_axis to apply the order to a:

import numpy as np

a = np.array([[7, -1, 0, 5],
              [2, 5.2, 4, 2],
              [3, -2, 1, 4]])

s = np.argsort(abs(a), axis=0)
a = np.take_along_axis(a, s, axis=0)
print(a)

a:

[[ 2.  -1.   0.   2. ]
 [ 3.  -2.   1.   4. ]
 [ 7.   5.2  4.   5. ]]

Upvotes: 3

Related Questions