首页 > 解决方案 > argsort 没有正确排序二维数组?

问题描述

我整天都被困在这上面,因为我真的看不出它哪里出了问题。

x=[[9.62825826e-04 7.54653307e+00 1.54219786e+01 1.56003006e+01
  7.56356875e+00]
 [2.13913061e+01 7.99323940e-01 4.54427893e+01 2.40201556e+01
  1.69257932e+01]
 [4.52324126e+01 4.54569526e+01 9.69601669e-03 4.59271880e+01
  2.85163398e+01]
 [4.54089845e+01 2.32183545e+01 4.59253670e+01 2.47722494e-03
  2.36843962e+01]
 [2.14375302e+01 1.69550555e+01 2.85025533e+01 2.44858206e+01
  7.98947124e-01]] 

i=x.argsort(axis=None) #axis=None to flatten whole array and sort over all values
j=np.reshape(i, (x.shape)) #reshape the sorted indices in a meaningful way

for k in tree1.keys(): #just enumerating over some dictionaries that form part of my code, not necessary to know what they are
    for p in tree2.keys(): #basically just counting the length of the array in x and y directions
        if j[k][p]==0: #to find lowest value value indices, so i can access the value later
            print("heres the index of that value", k,p)
            
print(j)

结果:

heres the index of that value 0 0
[[ 0 18 12 24  6]
 [ 1  4  2  3  9]
 [21  5 20 16 19]
 [ 8 23 22 14 10]
 [15  7 11 17 13]]

这没有错。但然后看它的第二低,即j[k][p]==1在 for 循环中 - 它给出指示值的索引2.13913061e+01,这显然是错误的..它应该给出(3,3),值为2.47722494e-03。我真的看不出有什么问题,因为我认为阵列的扁平化是可能绊倒它的主要因素 - 但因为它是扁平的,我不需要担心轴,我真的很困惑......

标签: pythonarrayssorting

解决方案


您正在考虑argsort错误方法的结果。的结果argsort是索引列表,按数组中的值排序。因此,索引在结果中的位置表示排序后数组中列表中第二个值的位置,而不是原始数组中倒数第二个值的位置。1argsort

扁平化数组的结果argsort如下:

>>> x.argsort(axis=None)
array([ 0, 18, 12, 24,  6,  1,  4,  2,  3,  9, 21,  5, 20, 16, 19,  8, 23,
       22, 14, 10, 15,  7, 11, 17, 13], dtype=int64)

因此,第二低的值18在原始数组中的 index 上,它确实与 index 匹配(3, 3)

>>> np.unravel_index(18, x.shape)
(3, 3)

在 的结果中argsort,索引1出现在数组中的第 6 位,这意味着该值x[1]是数组中的倒数第六。

因此,要找到第二低的值,您不应该1在 的结果中查找该值argsort,而应该只取结果中的第二个索引。


推荐阅读