-1

Say I have a numpy array of strings:

arr = np.array(['cat', 'dog', 'bird', 'swiss army knife'])

and I want to remove the string 'swiss army knife'.

What is the best way to do this?

It seems like something that should be very straight forward, but yet I haven't found a solution that doesn't involve sorting and/or finding the index of the element and use that to slice the selection of the array that's needed.

np.delete doesn't seem to work for strings.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
juioloiu
  • 43
  • 5
  • You can just write it without that entry - `arr = np.array(['cat', 'dog', 'bird])` – Sayse Apr 26 '22 at 14:24
  • What exactly do you want to get as result? An array with length reduced by one? Or an array with the same length but the string replaced by some "empty" value? – mkrieger1 Apr 26 '22 at 14:25
  • Are you saying that [this](https://stackoverflow.com/a/55864896) doesn't work? – mkrieger1 Apr 26 '22 at 14:31

4 Answers4

0

I hope this is works for you.

import numpy as np
arr = np.array(['cat', 'dog', 'bird', 'swiss army knife'])
result = np.where(arr=='swiss army knife')[0]
arr = np.delete(arr,result)
print(arr)
codester_09
  • 5,622
  • 2
  • 5
  • 27
0

just by masking:

mask = arr != 'swiss army knife'
result = arr[mask]
# ['cat' 'dog' 'bird']

or in one line as arr[arr != 'swiss army knife']

Ali_Sh
  • 2,667
  • 3
  • 43
  • 66
0

There's no method to erase a value from a np.array based on the array's value. Numpy's delete erase value based on index. So, in this case, it would be like:

arr = np.array(['cat', 'dog', 'bird', 'swiss army knife'])
arr = np.delete(arr, 3)

Instead, you could just use:

arr = np.array(['cat', 'dog', 'bird', 'swiss army knife'])
arr = arr[arr != 'swiss army knife']

or

arr = np.array(['cat', 'dog', 'bird', 'swiss army knife'])
arr = np.delete(arr, np.argwhere(arr == 'swiss army knife'))
  • Welcome SO, It is better to do not put the same answer as others after they have posted their own. The second proposed method is the same as mine and AJP. Just consider this point for your future answers. – Ali_Sh Apr 26 '22 at 15:16
-1
arr = np.array(['cat', 'dog', 'bird', 'swiss army knife'])
new_arr = np.array([i for i in arr if i != 'swiss army knife'])
Andrey Lukyanenko
  • 3,679
  • 2
  • 18
  • 21