【问题标题】:How to find row number and column number of a specific element in a multi dimensional array created with numpy?如何在使用 numpy 创建的多维数组中查找特定元素的行号和列号?
【发布时间】:2020-11-22 15:09:31
【问题描述】:

在python中使用numpy创建的多维数组中

matrix=np.array[[0,0,0,0,0], [0,0,0,0,1], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] 

如果我们将其视为矩阵。有没有办法找到元素'1'或矩阵内任何其他特定元素的行号和列号?

【问题讨论】:

  • 使用 np.where() ,

标签: python arrays numpy matrix multidimensional-array


【解决方案1】:

一种可能的解决方案是使用 np.argwhere:

np.argwhere(matrix == 1)

但请注意,您的数组可以包含 多个 仅具有此值的元素, 所以它返回一个 2-D 数组,其中每一行包含找到的每个元素的索引。

如果您只想要第一个这样的元素,请运行:

np.argwhere(matrix == 1)[0]

这次你会得到一个一维数组,包含2个元素(行号和列号)。

【讨论】:

  • 感谢您的建议顺便说一句,我对其进行了一些改进,就像你做np.where(matrix==1) 输出将是元组,我们可以通过元组解包res=np.where(matrix==1) 和@ 来检索行和列的值987654325@ 那么我们可以单独使用'a'和'b'
猜你喜欢
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多