Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a row based on a condition from a numpy array?

From the following array :

test = np.array([[1,2,'a'],[4,5,6],[7,'a',9],[10,11,12]])

How can I delete the rows that contain 'a' ? Expected result :

array([[ 4,  5,  6],
   [10, 11, 12]])
like image 585
G F Avatar asked Dec 14 '17 17:12

G F


People also ask

How do I remove a specific value from a NumPy array?

Use numpy.delete(arr, obj) with obj as a list of indices to remove the elements at each index from arr .

How do you remove certain values from an array in Python?

You can use the pop() method to remove an element from the array.

How do I delete multiple rows in NumPy?

Delete multiple rows using slice We can delete multiple rows and rows from the numpy array by using numpy. delete() function using slicing.


2 Answers

Note, numpy supports vectorized comparisons:

>>> test
array([[1, 2, 'a'],
       [4, 5, 6],
       [7, 'a', 9],
       [10, 11, 12]], dtype=object)
>>> test == 'a'
array([[False, False,  True],
       [False, False, False],
       [False,  True, False],
       [False, False, False]], dtype=bool)

Now, you want the rows where all are not equalt to 'a':

>>> (test != 'a').all(axis=1)
array([False,  True, False,  True], dtype=bool)

So, simply select the rows with the mask:

>>> row_mask = (test != 'a').all(axis=1)
>>> test[row_mask,:]
array([[4, 5, 6],
       [10, 11, 12]], dtype=object)
like image 170
juanpa.arrivillaga Avatar answered Sep 19 '22 17:09

juanpa.arrivillaga


Also, like this maybe? (Inspired from one of my another answers )

In [100]: mask = ~(test == 'a')

In [101]: mask
Out[101]: 
array([[ True,  True, False],
       [ True,  True,  True],
       [ True, False,  True],
       [ True,  True,  True]], dtype=bool)

In [102]: test[np.all(mask, axis=1), :]
Out[102]: 
array([['4', '5', '6'],
       ['10', '11', '12']],
      dtype='<U21')

But, please note that here we're not deleting any rows from the original array. We're just slicing out the rows which doesn't have the alphabet a.

like image 42
kmario23 Avatar answered Sep 19 '22 17:09

kmario23