Home > Software design >  How to sort parts of a numpy 2D array by second column?
How to sort parts of a numpy 2D array by second column?

Time:05-20

I am currently working on a computer vision project with python and openCV. I have a 2D numpy array like this:

 [100  38  18]
 [134 332  16]
 [136 200  16]
 [136 288  15]
 [138 160  17]
 [138 246  15]
 [140  76  12]
 [140 116  12]
 [142  34  14]

The 2D array is already sorted by the first column. This works fine. Now I need to sort pakets of 3 rows by the second column. This is the result I need to achieve:

 [100  38  18]
 [136 200  16]
 [134 332  16]
 [138 160  17]
 [138 246  15]
 [136 288  15]
 [142  34  14]
 [140  76  12]
 [140 116  12]

How can I achieve this?

CodePudding user response:

Just by NumPy, not looping:

sort_ = np.argsort(np.split(a[:, 1], a.shape[0] // 3))
# [[0 2 1]
#  [1 2 0]
#  [2 0 1]]

sort_  = np.linspace(0, a.shape[0] - 3, a.shape[0] // 3, dtype=np.int64)[:, None]
# [[0 2 1]
#  [4 5 3]
#  [8 6 7]]

a = a[sort_.ravel()]

CodePudding user response:

Consider reshaping your data into 3d, then use for loop to sort each array and cast back into an np.array

np.array([sorted(i, key = lambda x: x[1]) for i in ar.reshape(3, -1, ar.shape[1])]).reshape(ar.shape)
 
array([[100,  38,  18],
       [136, 200,  16],
       [134, 332,  16],
       [138, 160,  17],
       [138, 246,  15],
       [136, 288,  15],
       [142,  34,  14],
       [140,  76,  12],
       [140, 116,  12]])

CodePudding user response:

I see no other way than to use a loop

let A be your array

output = np.zeros((0, 3))
for i in range(int(A.shape[0]/3)):
    output = np.vstack((output, A[3*i   np.argsort(A[3*i:3*(i 1), 1])]))

Note: I'm assuming that your array has a number of lines which is a multiple of 3

  • Related