I have a tensor like
a = torch.Tensor([3,2,7,9,2,9, 9])

However, I need the values to start from 0 and go to n-1 where n is the number of unique elements in a. One possible way to compute this seems to be:
r = torch.zeros_like(a)
for i,el in enumerate(torch.unique(a)):
    r[a == el] = i

giving
tensor([1., 0., 2., 3., 0., 3., 3.])

Is there a more efficient way to compute this (possibly avoiding the unique and loop which takes a bit of time as I am having a quite big number of different elements ~10k and a very large a) ?
Thanks!