Create a column which increments value for changes in another row

后端 未结 3 1316
逝去的感伤
逝去的感伤 2021-02-09 09:55

I have a dataframe with two columns as below:

Var1Var2
a   28
b   28
d   28
f   29
f   29
e   30
b   30
m   30
l   30
u   31
t   31
t   31

I\'d

3条回答
  •  萌比男神i
    2021-02-09 10:18

    Using category

    df.Var2.astype('category').cat.codes.add(1)
    Out[525]: 
    0     1
    1     1
    2     1
    3     2
    4     2
    5     3
    6     3
    7     3
    8     3
    9     4
    10    4
    11    4
    dtype: int8
    

    Updated

    from itertools import groupby
    grouped = [list(g) for k, g in groupby(df.Var2.tolist())]
    np.repeat(range(len(grouped)),[len(x) for x in grouped])+1
    

提交回复
热议问题