【问题标题】:finding index for min element in a row in numpy gives error elementwise == comparison failed在numpy的一行中查找最小元素的索引会给出错误元素==比较失败
【发布时间】: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 有效。另外,我注意到我的方法适用于没有警告的一维数组,但不适用于二维数组。

标签: python numpy


【解决方案1】:

使用np.argmin 查找索引:

min_indices = np.argmin(dist, axis=1)
min_tuples = [(row, col) for row, col in enumerate(min_indices)]
# outputs: array([1, 1, 1, 1, 2, 4, 4, 0, 3, 3])
# [(0, 1),
   (1, 1),
   (2, 1),
   (3, 1),
   (4, 2),
   (5, 4),
   (6, 4),
   (7, 0),
   (8, 3),
   (9, 3)]

FWIW,此信息可通过 np.min??ipython shell 中访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2017-09-12
    • 2021-03-04
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多