【问题标题】:argsort isnt sorting the 2d array properly?argsort 没有正确排序二维数组?
【发布时间】:2021-03-12 18:34:49
【问题描述】:

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

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

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

【问题讨论】:

    标签: python arrays sorting


    【解决方案1】:

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

    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 上,它确实与索引(3, 3) 匹配:

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

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

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

    【讨论】:

    • 完美,非常感谢!有些不是那么直观,但有道理。再次感谢!
    猜你喜欢
    • 2016-10-17
    • 2023-03-09
    • 2013-05-16
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多