【问题标题】:Find indices of zero array into an array将零数组的索引查找到数组中
【发布时间】:2019-11-30 11:07:27
【问题描述】:

我有一个 numpy 数组

my_array = np.array([[1,2,3,4],[5,6,7,8],[0,0,0,0],[1,2,3,4],[0,0,0,0],[0,0,0,1]])

当数组仅包含零值时,我想获取所有索引:

index 2 -> [0,0,0,0]
index 4 -> [0,0,0,0]

存在类似问题的讨论:Find indices of elements equal to zero in a NumPy array

但是在这个解决方案中,我们得到的值等于零,而不是我想要的零数组。

感谢您的帮助。

【问题讨论】:

    标签: arrays python-3.x


    【解决方案1】:

    您可以使用 np.argwherenp.all 来获取所有元素 == 0 的行的索引:

    In [11] np.argwhere((my_array == 0).all(axis=1))
    Out[11]: 
    array([[2],
           [4]], dtype=int64)
    

    np.nonzero 而不是np.argwhere 会产生更好的输出:

    In [12] np.nonzero((my_array == 0).all(axis=1))
    Out[12]: (array([2, 4], dtype=int64),)
    

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2016-06-09
      • 2021-01-29
      • 2011-06-03
      • 1970-01-01
      • 2014-05-08
      • 2019-07-24
      • 1970-01-01
      相关资源
      最近更新 更多