【发布时间】:2018-03-08 15:49:57
【问题描述】:
我有一个 2D numpy 数组,我试图找到与每行中最小元素对应的索引。我的代码如下所示:
dist=np.array([[0.15, 0.07, 0.14, 0.17, 0.15],
[0.16, 0.07, 0.14, 0.19, 0.15],
[0.10, 0. , 0.10, 0.14, 0.09],
[0.07, 0. , 0.06, 0.05, 0.14],
[0.10, 0.10, 0. , 0.17, 0.06],
[0.08, 0.10, 0.07, 0.15, 0.03],
[0.05, 0.09, 0.06, 0.13, 0. ],
[0. , 0.10, 0.10, 0.07, 0.05],
[0.06, 0.14, 0.16, 0.02, 0.11],
[0.07, 0.14, 0.17, 0. , 0.13]])
x= dist.min(axis=1)
print x
idx= np.where(dist==x)
print idx
print a[idx]
我得到以下输出
[0.07 0.07 0. 0. 0. 0.03 0. 0. 0.02 0. ]
(array([], dtype=int64),)
[]
/Library/Python/2.7/site-packages/ipykernel_launcher.py:13: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.
del sys.path[0]
由于某种原因,索引值为空,我也收到警告/错误?相反,我想检索的索引是 (0,1)、(1,1)、(2,1) 等,对应于每行中的最小元素。
【问题讨论】:
-
np.argmin(dist, axis=1)返回每行中最小值的索引。要告诉您发出警告的原因,您必须提供b。 Numpy 不鼓励比较不同大小的数组,也许这就是为什么 -
b 是一个错字,我已经用我使用的东西修复了它。 np.argmin 有效。另外,我注意到我的方法适用于没有警告的一维数组,但不适用于二维数组。