How could I remove the rows of an array if one of the elements of the row does not satisfy a condition?

后端 未结 2 1012
一个人的身影
一个人的身影 2020-12-20 06:33

I would like to remove the rows of an array when the elements of third column of the array are less than specific amount. For example:

a=np.array([[2331.13,1         


        
相关标签:
2条回答
  • 2020-12-20 07:03

    I think the most straight forward way to remove rows or columns is to use np.delete

    >>> a = np.arange(16).reshape(4,4)
    >>> a
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    >>> a[:,2]
    array([ 2,  6, 10, 14])
    >>> to_remove = a[:,2] < 7
    >>> to_remove
    array([ True,  True, False, False], dtype=bool)
    >>> new_a = np.delete(a, to_remove, axis=0)
    >>> new_a
    array([[ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    

    In one line:

    new_a = np.delete(a, a[:,2] < 7, axis=0)
    
    0 讨论(0)
  • 2020-12-20 07:04

    You can do:

    a[a[:,2]>=15.0, :]
    

    Note the inversion of a[:,2]<15.0 to a[:,2]>=15.0, so that you're describing rows that you want to keep rather than remove.

    If inverting your condition isn't as simple as that, you could also use ~:

    a[~(a[:,2]<15.0), :]
    
    0 讨论(0)
提交回复
热议问题