Search code examples
arrayspython-3.xstringnumpynumpy-ndarray

How to remove numpy array row which matches the string in list


I have got an array which looks like

array = array([['Mango', 0.75, 0.25],
               ['Honey', 0.75, 0.25],
               ['Grape', 0.625, 0.375],
               ['Pineapple', 0.5, 0.5]], dtype=object)

and a list item = {'Honey','Grape'} now, have to remove the rows from the array which matches the items in the list.

Expected Output:

array = array([['Mango', 0.75, 0.25],
               ['Pineapple', 0.5, 0.5]], dtype=object)

Have tried the below code but somehow it doesn't work.

array[:] = [x for x in array[:,0] if item not in x]

Help me with this. Thanks in advance!


Solution

  • You can use:

    out = array[ ~np.isin(array[:, 0], item) ]
    

    out:

    array([['Mango', 0.75, 0.25],
           ['Pineapple', 0.5, 0.5]], dtype=object)
    

    but you may want to have a look at a np.recarray or a pandas DataFrame, which is more suited to this kind of data.