简体   繁体   English

如何按第二列对 numpy 2D 数组的部分进行排序?

[英]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.我目前正在使用 python 和 openCV 进行计算机视觉项目。 I have a 2D numpy array like this:我有一个像这样的二维 numpy 数组:

 [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.现在我需要按第二列对 3 行的包进行排序。 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?我怎样才能做到这一点?

Consider reshaping your data into 3d, then use for loop to sort each array and cast back into an np.array考虑将数据重塑为 3d,然后使用 for 循环对每个数组进行排序并转换回 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]])

Just by NumPy, not looping:只是通过 NumPy,而不是循环:

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

I see no other way than to use a loop除了使用循环,我别无他法

let A be your arrayA成为你的数组

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注意:我假设您的数组有许多行是 3 的倍数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM