【问题标题】:numpy equivalent to list.index [duplicate]numpy 相当于 list.index [重复]
【发布时间】:2021-07-25 12:27:55
【问题描述】:

在 Python 中,我可以使用 list.index 来查找元素的索引,例如[1,2,3,4].index(1) 返回 0,因为元素 1 出现在位置 0。我想用多维数组来做到这一点。也就是说,我希望能够写出类似的东西

x = np.array([[0, 1, 2],
              [3, 4, 5]])
y = np.array([0, 1, 2])
print(x.index(y))

输出应该是0,因为目标元素再次位于第一个位置。

使用内置的 list.index 方法不起作用,因为 numpy 数组的 == 运算符返回一个数组而不是布尔值。而np.argwhere 不做任何广播。我知道我总能做到

idx = 0
while idx < x.shape[0] and (x[idx] != y).any():
  idx += 1
print(idx)

但这感觉太笨拙了!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    有几种方法。按照这个例子(Find matching rows in 2 dimensional numpy array):

    >>> np.where((x == y).all(axis=1))
    (array([0]),)
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 2012-05-21
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多