'How to sort parts of a numpy 2D array by second column?

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?



Solution 1:[1]

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()]

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2