【问题标题】:How to the function 'where' generate this array? [duplicate]函数'where'如何生成这个数组? [复制]
【发布时间】:2019-06-26 14:02:06
【问题描述】:
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))

x>5 到底是什么意思?生成的数组看起来很神秘。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    这是一个带有行和列索引的元组。 x > 5 返回一个与x 形状相同的布尔数组,其中满足条件的元素设置为True,否则返回False。根据the documentation np.where 将在没有其他参数时回退到condition.nonzero。对于您给定的示例,所有大于 5 的元素恰好在行 2 中,并且所有列都满足条件,因此是 [2, 2, 2] (rows), [0, 1, 2] (columns)。请注意,您可以使用此结果来索引原始数组:

    >>> x[np.where(x > 5)]
    [6 7 8]
    

    【讨论】:

      【解决方案2】:

      通常的语法是np.where(condition, res_if_true, res_if_false)。只有第一个参数,这是一个特例described in the docs

      当仅提供条件时,此函数是 np.asarray(condition).nonzero().

      所以先计算x > 5

      arr = x > 5
      print(arr)
      # array([[False, False, False],
      #        [False, False, False],
      #        [ True,  True,  True]])
      

      既然已经是数组,计算arr.nonzero()

      print(arr.nonzero())
      # (array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))
      

      这将返回非零元素的索引。元组的第一个元素表示axis=0 的坐标,第二个元素表示axis=1 的坐标,即第二行和最后一行中的所有值都大于5。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 2017-06-18
        • 2016-10-05
        • 2019-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多