【问题标题】:Element wise comparison in an array of arrays in NumpyNumpy中数组数组中的元素比较
【发布时间】:2017-01-19 16:37:02
【问题描述】:

我有以下shape(5,2,3) 数组,它是2 * 3 数组的集合。

a = array([[[ 0,  2,  0],
    [ 3,  1,  1]],

   [[ 1,  1,  0],
    [ 2,  2,  1]],

   [[ 0,  1,  0],
    [ 3,  2,  1]],

   [[-1,  2,  0],
    [ 4,  1,  1]],

   [[ 1,  0,  0],
    [ 2,  3,  1]]])

1)如何检查这个数组中是否存在2 * 3 数组,其中至少有一个元素为负数?

#which is this:
[[-1,  2,  0],
[ 4,  1,  1]]

2) 之后如何从a 中删除上面找到的2 * 3 数组?

非常感谢矢量化实现,但循环也很好。

【问题讨论】:

    标签: python arrays numpy multidimensional-array vectorization


    【解决方案1】:

    你可以做-

    a[~(a<0).any(axis=(1,2))]
    

    或与.all() 等效,从而避免inverting -

    a[(a>=0).all(axis=(1,2))]
    

    示例运行 -

    In [35]: a
    Out[35]: 
    array([[[ 0,  2,  0],
            [ 3,  1,  1]],
    
           [[ 1,  1,  0],
            [ 2,  2,  1]],
    
           [[ 0,  1,  0],
            [ 3,  2,  1]],
    
           [[-1,  2,  0],
            [ 4,  1,  1]],
    
           [[ 1,  0,  0],
            [ 2,  3,  1]]])
    
    In [36]: a[~(a<0).any(axis=(1,2))]
    Out[36]: 
    array([[[0, 2, 0],
            [3, 1, 1]],
    
           [[1, 1, 0],
            [2, 2, 1]],
    
           [[0, 1, 0],
            [3, 2, 1]],
    
           [[1, 0, 0],
            [2, 3, 1]]])
    

    【讨论】:

      【解决方案2】:

      使用any:

      In [10]: np.any(a<0,axis=-1)
      Out[10]: 
      array([[False, False],
             [False, False],
             [False, False],
             [ True, False],
             [False, False]], dtype=bool)
      

      或者更完整,如果你想要(2,3)数组的对应索引:

      In [22]: np.where(np.any(a<0,axis=-1).any(axis=-1))
      Out[22]: (array([3]),)
      # Or as mentioned in comment you can pass a tuple to `any` np.where(np.any(a<0,axis=(1, 2)))
      

      你也可以通过简单的索引来获取数组:

      In [27]: a[np.any(a<0, axis=(1, 2))]
      Out[27]: 
      array([[[-1,  2,  0],
              [ 4,  1,  1]]])
      

      【讨论】:

      • 您也可以将元组传递给 np.any:np.any(a&lt;0, axis=(1, 2))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多