When using torch.sort(), how do I assign the minimal index to those same elements?

Like if I have a Tensor

a = [1, 2, 2, 3]

If I perform torch.sort(a), then the index it returns will be

[0, 1, 2, 3]

What if I want to get the result like

[0, 1, 1, 3]

I know there’s a function exists in scipy “scipy.data.rankdata”, in the function, I can specify the method it uses when ranking the data. But how can I achieve the similar goal with pytorch?

torch.unique(x, sorted=True, return_inverse=True)
(tensor([1, 2, 3]), tensor([0, 1, 1, 2]))

But the result I expect to get is

[0, 1, 1, 3]

That is, when same elements appear in an array, the returned index will not be “continous”. Are there any other ways to do it?

I dont think there’s a direct way to do [0, 1, 1, 3]. Unique gives you what you want from an ordering perspective, but does not account for the right magnitude,

It’s also useful. Thanks anyway!

For anyone who stumbles over this thread again, a small modification to @smth 's answer works:

import torch
x = torch.tensor([1, 2, 2, 3])
uq_vals,inverse_ixs,counts = torch.unique(x, sorted=True, return_inverse=True,return_counts=True)
cumsum_counts = counts.cumsum(dim=0)
possible_ranks = torch.zeros_like(counts)
possible_ranks[1:] = cumsum_counts[:-1]
ranks = possible_ranks[inverse_ixs]