Q:

Array of index values for unique elements in list

I have the following list:
x = np.array([1, 1, 2, 2, 2])

with np.unique values of [1, 2]
How do I generate the following list:
[1, 2, 1, 2, 3]

i.e. a running index from 1 for each of the unique elements in the list x.

A:

you can use pandas.cumcount() after grouping by the value itself, it does exactly that:

Number each item in each group from 0 to the length of that group - 1.

try this:
import numpy as np
import pandas as pd

x = np.array([1, 1, 2, 2, 2])

places = list(pd.Series(x).groupby(by=x).cumcount().values + 1)
print(places)

Output:
[1, 2, 1, 2, 3]

