代码之家  ›  专栏  ›  技术社区  ›  user697911

如何使用函数“where”生成此数组?[副本]

  •  -1
  • user697911  · 技术社区  · 7 年前
    >>> x = np.arange(9.).reshape(3, 3)
    >>> np.where( x > 5 )
    (array([2, 2, 2]), array([0, 1, 2]))
    

    x>5

    2 回复  |  直到 7 年前
        1
  •  1
  •   a_guest    7 年前

    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
  •  0
  •   jpp    7 年前

    通常的语法是 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