我看不出这个问题哪里出了问题:
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)
这是该值 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)
,值为 2.47722494e-03
。我看不出有什么问题,因为我认为数组的扁平化是可能使它出错的主要因素_但由于它是扁平的,所以我不需要担心轴。
您正在以错误的方式思考
argsort
的结果。 argsort
的结果是索引列表,按数组中的值排序。因此,1
结果中索引argsort
的position表示排序数组中列表中第二个值的位置,而不是原数组中第二低值的位置。
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]
是数组中第六小的值。因此,要找到第二低的值,您不应该在
1
的结果中查找值
argsort
,而应该只在结果中查找第二个索引。