python - 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
。我真的看不出有什么问题,因为我认为阵列的扁平化是可能绊倒它的主要因素 - 但因为它是扁平的,我不需要担心轴,我真的很困惑......
解决方案
您正在考虑argsort
错误方法的结果。的结果argsort
是索引列表,按数组中的值排序。因此,索引在结果中的位置表示排序后数组中列表中第二个值的位置,而不是原始数组中倒数第二个值的位置。1
argsort
扁平化数组的结果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
,而应该只取结果中的第二个索引。
推荐阅读
- colors - mayavi 颜色数量和自定义色阶
- pyspark - 基于Filter RDD-PySpark的映射输出
- android - 如何将字节数组转换为位图?
- python - 长字典排序列表
- angular - 角度输入设置器仅触发一次
- java - Slack 请求验证:无法使用签名密钥计算匹配的请求摘要
- kubernetes - 无法加入集群:在 kubeadm 加入期间连接被拒绝
- javascript - 单击标题“价格”后,如何对表格行进行升序和降序排序?
- math - 用陀螺仪测量绕一个轴的旋转
- javascript - 如何从与angularjs中第一个数组大小相同的两个数组中获取一个数组?