Home > Software engineering >  How to remove numpy array row which matches the string in list
How to remove numpy array row which matches the string in list

Time:01-30

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!

CodePudding user response:

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.

CodePudding user response:

Another possible solution, using numpy broadcasting:

a[np.all(a[:,0][:, None] != itens, axis=1), :]

Output:

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