简体   繁体   English

(反向)按列对二维 numpy 数组进行排序

[英](Inverse-) Sorting 2d numpy array column-wise

The following code sorts an 2d numpy array column-wise forth and back以下代码按列来回对 2d numpy 数组进行排序

import numpy as np
#Column-wise sort and inverse sort of image (2d array)
nrows = 10
ncols = 5
a = np.random.randint(nrows, size=(nrows, ncols))
a_sorted = np.sort(a, axis=0)

ori_indices = np.zeros_like(a)
for c in range(ncols):
    ori_indices[:,c] = np.argsort(np.argsort(a[:,c]))
#Do some work on sorted array, like e.g row-wise filtering
#After processing sorted array, move it back to original order
a_backsorted = np.zeros_like(a)
for c in range(ncols):
    a_backsorted[:,c] = a_sorted[:,c][ori_indices[:,c]]

print (a); print ()
print (a_backsorted); print ()
print (a_sorted); print ()

The code work as is but I guess there is a more efficient implementation without for loop (using fancy indexing)代码按原样工作,但我想有一个更有效的实现没有 for 循环(使用花哨的索引)

You can try a_sorted[::-1] to reverse the array您可以尝试a_sorted[::-1]反转数组

print (a_sorted); print ()
print (a_sorted[::-1])

[[0 0 0 2 0]
 [2 0 0 2 2]
 [4 0 2 6 4]
 [4 2 3 7 5]
 [4 4 4 7 6]
 [5 5 4 8 7]
 [6 5 4 8 7]
 [7 6 8 9 8]
 [8 7 9 9 9]
 [8 8 9 9 9]]

[[8 8 9 9 9]
 [8 7 9 9 9]
 [7 6 8 9 8]
 [6 5 4 8 7]
 [5 5 4 8 7]
 [4 4 4 7 6]
 [4 2 3 7 5]
 [4 0 2 6 4]
 [2 0 0 2 2]
 [0 0 0 2 0]]
#Column-wise sort and inverse sort of image (2d array)
import numpy as np
#Define random array and sort it
nrows = 10
ncols = 5
a = np.random.randint(nrows, size=(nrows, ncols))
a_sorted = np.sort(a, axis=0)
#Save original order of columns
ori_indices = np.argsort(np.argsort(a, axis=0), axis=0)
#Do some work on sorted array, like e.g row-wise filtering.
#....
#After processing sorted array, move it back to original order:
c=np.array([[i] for i in range(ncols)]).T
a_backsorted = a_sorted[ori_indices, c]
#Check results
print (a); print ()
print (a_backsorted); print ()
print (a_sorted); print ()
import numpy as np
nrows = 10; ncols = 5
a = np.random.randint(nrows, size=(nrows, ncols))
a_sorted = np.sort(a, axis=0)
a_backsorted = np.zeros_like(a)
c = np.array([[i] for i in range(ncols)]).T
a_backsorted[np.argsort(a, axis=0), c] = a_sorted

The reverting of the column-wise sorting is done by inserting the values of the sorted array at the argsorted positions in the backsorted array.通过将已排序数组的值插入到反向排序数组中的 argsorted 位置来完成按列排序的恢复。 Since this is done columnwise, the argsorted positions are paired with the columns represented in the c array由于这是按列完成的,因此 argsorted 位置与 c 数组中表示的列配对

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

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