Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete specific rows from a numpy array using a condition?

This is the code

a = np.array([[ 0,  1],
              [ 3, 11],
               [4,2]])

This is what I tried

a= a[a[0]>0,:]

It works fine when I only have two elements, but anything more it throws an error.What I am trying to do is that in the first column if there's a value less than one than I need to delete that entire row.

so the expected output is

     ([ 3, 11],
     [4,2]])

I was hoping for a solution which I could generalize even if there were more than 2 elements per item such as

    ([2,3,4,5],
     [8,2,4,6],
     [2,4,9,1],
     [5,3,2,0],)

then the application of the code will give a result such as

    ([2,3,4,5],
     [8,2,4,6],
     [2,4,9,1],)

Any suggestions.

like image 435
Amit Singh Parihar Avatar asked Aug 05 '26 09:08

Amit Singh Parihar


1 Answers

For just the first column use a[:,0] > 0 which will pull all the values from the first column and check which are > 0 or whatever condition you want:

 In [50]: a = np.array([[ 0,  1],
              [ 3, 11],
               [4,2]])

In [51]: a[a[:,0] > 0]
Out[51]: 
array([[ 3, 11],
       [ 4,  2]])

You can use all if you want to check all values in each row:

In [43]: a = np.array([[ 0,  1],
              [ 3, 11],
               [4,2]])

In [44]: a[(a >= 0).all(axis=1)]
Out[44]: 
array([[ 3, 11],
       [ 4,  2]])

In [45]: a = np.array ([[2,3,4,5],
                       [8,2,4,6],
                       [2,4,9,1],
                        [5,3,2,0]])

In [46]: a[(a > 0).all(axis=1)]
Out[46]: 
array([[2, 3, 4, 5],
       [8, 2, 4, 6],
       [2, 4, 9, 1]])
like image 65
Padraic Cunningham Avatar answered Aug 08 '26 02:08

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!