0

I have a tensor say t = [1, 2, 3, 4, 5, 6, 7, 8, 9] and a list of indices I want to remove like d = [0, 2, 5].

Doing t[d] gives me the subtensor with the elements I want to remove.

How can I used d to get the subtensor with all the elements except the ones indexed in d. There must be something like t[~d], right?

Something like numpy's numpy.delete.

Michael
  • 325
  • 3
  • 14
  • `np.delete` is not a simple function. It does different things depending dimensions and index. You might want to read its code. – hpaulj May 30 '22 at 07:31
  • Does this answer your question? [How to remove specific elements in a numpy array](https://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array) – Ali_Sh May 30 '22 at 07:31
  • Yup, that last way to create a mask seems to work and it's pretty fast. Feel free to post it as an answer or I guess I can. Thx! – Michael May 30 '22 at 07:48

1 Answers1

0

delete uses logic like

mask= np.ones(t.shape, dtype=bool)
mask[d] = False
res = t[mask]

mask is a bool that is true for all indices we want to keep. This is the simple 1d version.

In [3]: t=np.arange(1,10); d= np.array([0,2,5])

In [4]: mask = np.ones(t.shape, bool)
In [5]: mask[d] = False
In [6]: mask
Out[6]: array([False,  True, False,  True,  True, False,  True,  True,  True])

In [7]: t[mask]
Out[7]: array([2, 4, 5, 7, 8, 9])
hpaulj
  • 221,503
  • 14
  • 230
  • 353