【问题标题】:Python: Indices of all rows in array with non-zero entries onlyPython:仅具有非零条目的数组中所有行的索引
【发布时间】:2017-04-25 02:01:37
【问题描述】:

numpy 数组中,我如何才能找到 只有非零条目的所有行的索引。例如在数组中:

A = np.array([[ 1,  0,  5],
              [25,  2,  0],
              [ 7,  8,  9],
              [ 0,  0,  4],
              [11, 14, 15]])

我希望将 [2,4] 作为输出,因为第 2 行和第 4 行是唯一所有条目均非零的行。

目前,我正在使用

B = A[np.all(A != 0, axis=1)]

获取一个数组,其中所有至少有一个零的行都已被丢弃。但我需要找到索引(即 2 和 4)。

【问题讨论】:

    标签: python arrays


    【解决方案1】:

    您的方法应该进行如下改动:

    np.where(np.all(A != 0, axis=1))[0].tolist()
    Out[284]: [2, 4]
    

    【讨论】:

      【解决方案2】:
      In [1]: A = np.array([[ 1,  0,  5],
                            [25,  2,  0],
                            [ 7,  8,  9],
                            [ 0,  0,  4],
                            [11, 14, 15]])
      
      In [2]: Indx1 = np.all(A != 0, axis=1) 
              print Indx1
      Out[2]: Indx1 = [False False  True False  True] 
      
      In [3]: Indx2 = np.where(Indx1==True)
              print Indx2
      Out[3]: (array([2, 4]),)
      
      In [4]: Indx = A[Indx2[0]]
              print Indx
      Out[4]: [2 4]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-23
        • 2020-12-31
        • 1970-01-01
        • 1970-01-01
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多