generate 1D tensor as unique index of rows of an 2D tensor (keeping the order and the original index)
This question is an updated version of generate 1D tensor as unique index of rows of an 2D tensor
Let's say we transform a 2D tensor to a 1D tensor by giving each, different row a different index, from 0 to the number of rows - 1.
[[1,4],[1,3],[1,2]] -&gt; [0,1,2]

But if there are same rows, we repeat the index, like this below, the &quot;original&quot; index is k-1 for the k-th row
[[1,4],[1,2],[1,2]] -&gt; [0,1,1]

Also if there is no repeat for the row (like the third row below), its index should be its original index, which is k-1 for the k-th row (for example 2 for [1,4]).
[[1,3],[1,3],[1,4]] -&gt; [0,0,2]

A longer example:
[[1,2],[4,3],[1,4],[1,4],[4,3],[1,2],[5,6],[7,8]] -&gt; [0,1,2,2,1,0,6,7]

How to implement this on PyTorch?

See the non-vectorized solution from @Michael
 d = {}; torch.tensor([d.setdefault(tuple(i.tolist()), e) for e, i in enumerate(t4)]) 

Another non-vectorized solution is
t4_list = t4.tolist(); torch.tensor(list(map(lambda x: t4_list.index(x), t4)))

