Delete element from multi-dimensional numpy array by value

前端 未结 5 1719
抹茶落季
抹茶落季 2020-12-18 10:06

Given a numpy array

a = np.array([[0, -1, 0], [1, 0, 0], [1, 0, -1]])

what\'s the fastest way to delete all elements of value -1

5条回答
  •  旧巷少年郎
    2020-12-18 11:00

    For almost everything you might want to do with such an array, you can use a masked array

    a = np.array([[0, -1, 0], [1, 0, 0], [1, 0, -1]])
    
    b=np.ma.masked_equal(a,-1)
    
    b
    Out[5]: 
    masked_array(data =
     [[0 -- 0]
     [1 0 0]
     [1 0 --]],
                 mask =
     [[False  True False]
     [False False False]
     [False False  True]],
           fill_value = -1)
    

    If you really want the ragged array, it can be .compressed() by line

    c=np.array([b[i].compressed() for i in range(b.shape[0])])
    
    c
    Out[10]: array([array([0, 0]), array([1, 0, 0]), array([1, 0])], dtype=object)
    

提交回复
热议问题