def approach1(g, v):
    id_arr2 = np.ones(v.size, dtype=int)
sf = np.flatnonzero(g[1:] != g[:-1]) + 1
id_arr2[sf[0]] = -sf[0] + 1
id_arr2[sf[1:]] = sf[:-1] - sf[1:] + 1
return id_arr2.cumsum().argsort(kind='mergesort')
sort dataframe by position in group then by that group