【问题标题】:Is there a way to find every index of an input value in a 2d array?有没有办法在二维数组中找到输入值的每个索引?
【发布时间】:2020-10-06 17:10:35
【问题描述】:

我一直在尝试在 python 中创建一个函数,该函数返回二维数组中每个重复值的 x,y 坐标。例如,如果我有数组和一个值,

array = [ [1 ,2 ,3]
          [2 ,3 ,1]
          [3 ,2, 1]]

search = 1

它会输出(0,0) (1,2) (2,2)

我一直在尝试使用一些函数,例如 np.where 或将其转换为 pandas 数据框并以这种方式进行搜索,但我不确定最好的方法。当我使用 np.where 时,它​​返回一个空数组,因为我使用的是长小数。我正在尝试在 200 x 200 的阵列上执行此操作。

【问题讨论】:

  • where 仅与条件数组一样好。如果array==.01 在任何地方都不为真,那么where 的结果将为空。搜索浮点值的精确匹配是不可靠的。

标签: python arrays pandas numpy indexing


【解决方案1】:

我们可以np.where PS:a 是你的数组

list(zip(*np.where(a==search)))
[(0, 0), (1, 2), (2, 2)]

正如 hpaulj 提到的

np.argwhere(np.isclose(a,search))
array([[0, 0],
       [1, 2],
       [2, 2]])

【讨论】:

  • 谢谢!如果我有一个长小数,最好的方法是什么?当我这样做时,它会输出一个空数组。
  • @JacksonFuson list(zip(*np.where(np.isclose(a,search))))
  • np.argwhere(cond) 执行np.transpose(np.where(cond))。您的zip(*) 是转置的列表版本。
  • 为了进一步用作索引,where 的结果通常比它的转置更有用。该数组元组是根据索引设计的。
猜你喜欢
  • 2021-10-01
  • 2022-01-18
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多