【问题标题】:numpy.where() with a 2d array and a 1d array in the conditionnumpy.where() 在条件中带有一个二维数组和一个一维数组
【发布时间】:2016-01-08 00:12:56
【问题描述】:

给定以下二维 numpy 数组:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])

我们可以使用np.where() 来获取满足特定条件的条目的索引。

>>> np.where(a == [4, 5, 6])
(array([0, 0, 0]), array([0, 1, 2])) 

到目前为止一切顺利:要返回的第一个数组是整数 4,5,6 出现在 a 中的行 idx,第二个数组是 where 4 的 col idx, 5,6 出现在a

>>> np.where(a == [4,5,8])
(array([0, 0]), array([0, 1])) 

为什么整数8没有被拾取?

>>> np.where(a == [6,8,9])       
(array([1, 1]), array([1, 2])) 

为什么整数6没有被拾取?

>>> np.where(a == [4,8,9])
(array([0, 1, 1]), array([0, 1, 2])) 

整数4怎么会被拾取?

【问题讨论】:

  • 这与where 无关 - 看看例如a == [4, 8, 9] 给你。
  • 如果您不知道 为什么 这就是您得到的结果,请注意 numpy 会将列表与数组中的每一行进行比较; 8 不在任何行的最后一位,6 不在第一位(但4 是)。

标签: python arrays numpy matrix


【解决方案1】:

感谢 jonrsharpe 在我的问题下方的 cmets,我能够理解发生了什么。

>>> > a = np.arange(5,10)
>>> a == [4,8,9]
array([[True, False, False],
       [False,  True,  True]], dtype=bool)

获取[4,8,9] 并针对a 的每个3 数组条目逐个元素地评估它们是否相等。

>>> np.where(a == [4,8,9])
(array([0, 1, 1]), array([0, 1, 2])) 

给出True 出现位置的行和列索引。

【讨论】:

  • 我认为np.transpose(np.where(a == [4,8,9])) 以更易读的方式生成行和列索引
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 2017-10-12
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多