Delete an element from torch.Tensor

11,845

Solution 1

You can first filter array through indices and then concat both

t.shape
torch.Size([1, 36])

t = torch.cat((t[:,:3], t[:,4:]), axis = 1)

t.shape
torch.Size([1, 35])

Solution 2

I think that doing this with indexing is more readable.

t[t!=t[0,3]]

The result is the same as with the cat solution from below.

BE CAREFUL: This will usually work for floats, but beware that if the value at [0,3] occurs more than once in the array, you will remove all occurrences of this item.

Solution 3

You can use numpy`s r_ indexing trick

y = x[:, np.r_[:3, 4:36]]
Share:
11,845
John Smith
Author by

John Smith

Updated on June 11, 2022

Comments

  • John Smith
    John Smith almost 2 years

    I'm trying to delete an item from a tensor.

    In the example below, How can I remove the third item from the tensor ?

    tensor([[-5.1949, -6.2621, -6.2051, -5.8983, -6.3586, -6.2434, -5.8923, -6.1901,
             -6.5713, -6.2396, -6.1227, -6.4196, -3.4311, -6.8903, -6.1248, -6.3813,
             -6.0152, -6.7449, -6.0523, -6.4341, -6.8579, -6.1961, -6.5564, -6.6520,
             -5.9976, -6.3637, -5.7560, -6.7946, -5.4101, -6.1310, -3.3249, -6.4584,
             -6.2202, -6.3663, -6.9293, -6.9262]], grad_fn=<SqueezeBackward1>)