Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading