How to remove an element from a 1-d tensor by index?

So I have a 1-d tensor T and an index i and need to remove i-th element from a tensor T, much like in pure python T.remove(i).

I’ve tried to do this:

i = 2
T = torch.tensor([1,2,3,4,5])
T =[T[0:i], T[i+1:-1]])

But it fails to bring in the last element (5 in this case).
Any suggestions?

Update, this works

i = 2
T = torch.tensor([1,2,3,4,5])
T =[T[0:i], T[i+1:]])
1 Like

Your solution should read
T =[T[0:i], T[i+1:]])
or equivalently
T =[T[:i], T[i+1:]])
(but there is probably a better way to do this)


Thank you guys, this solves the problem.
But there must be a way less clunky solution, I believe.

1 Like

how to remove by value??

1 Like

One possible way would be to index the tensor for all other values:

x = torch.arange(10)
value = 5
x = x[x!=value]

I’m getting this error

Expected object of scalar type Float but got scalar type Long for argument #2 'other'

Try to create value as a float type.

This won’t work if i = 0. Any other approach?

How about removing more than 1 elements by indices? Is there a faster way than looping ?

For example

i = [0,100,2,5,10, 200,500]
T =torch.randn(1000)

T_new =  T [whose elements not equal to elements in i]

I want to get the T_new without looping over i…

1 Like

T_new =[T[:i[0]], T[i[0]+1:i[1]], T[i[1]+1:i[2]],...])

Does that help?

Not fast enough I am afraid…

If i has a lot of values, a loop is probably your best bet. You could try using multi-processing.

Hello, I think, A more elegant way will be to use a function like:

import torch as th

def th_delete(tensor, indices):
    mask = th.ones(tensor.numel(), dtype=th.bool)
    mask[indices] = False
    return tensor[mask]

It can be used like this:

>>> a = th.arange(5)
>>> a
tensor([0, 1, 2, 3, 4])
>>> th_delete(a, [0, 3, 4])
tensor([1, 2])
>>> th_delete(a, [1])
tensor([0, 2, 3, 4])
>>> th_delete(a, th.tensor([1, 4]))
tensor([0, 2, 3])

And even like this:

>>> a = th.arange(5)
>>> a
tensor([0, 1, 2, 3, 4])
>>> th_delete(a, 1)
tensor([0, 2, 3, 4])

This is an elegant solution. Thanks.

may you suggest another way to do the same operation if value is not a scaler but another torch 1-d array?

Try this: