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

沿轴0的Numpy where条件语句

  •  1
  • dubbbdan  · 技术社区  · 6 年前

    Zc 包含n个二维数组元素。我想找到每个2D数组的索引 np.ones(Zc[i].shape) .

    a = np.zeros((5,5))
    b = np.ones((5,5))*4
    c = np.ones((5,5))
    d = np.ones((5,5))*2
    
    Zc = np.stack((a,b,c,d))
    
    for i in range(len(Zc)):
        a = np.ones(Zc[i].shape)
        b = Zc[i]
        if np.array_equal(a,b):
            print(i)
        else:
            pass 
    

    它回来了 2 . 上面的代码可以工作并返回正确的答案,但是我想知道是否有一种矢量化的方法来实现相同的结果?

    1 回复  |  直到 6 年前
        1
  •  0
  •   C. Braun    6 年前

    离开hpaulj的评论:

    >>> allones = (Zc == np.array(np.ones(Zc[i].shape))).all(axis=(1,2))
    >>> np.where(allones)[0][0]
    2