Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment variable for each group

I have the following data:

ID    Time
1     01-01-01
1     02-01-01
1     02-01-01
2     01-01-01

I would like to start with 0 and increase one by one for each new time by group ID. SO I need to get something like that

ID    Time       Result
1     01-01-01   0
1     02-01-01   1
1     02-01-01   1
2     01-01-01   0

Is there a smart way to do it shortly? (Note that this is just for illustration, real data is large enough.)

like image 778
user229519 Avatar asked Apr 25 '26 12:04

user229519


1 Answers

You can use groupby with pd.factorize:

df['Result'] = df.groupby('ID')['Time'].transform(lambda x: pd.factorize(x)[0])
df

Output:

   ID      Time  Result
0   1  01-01-01       0
1   1  02-01-01       1
2   1  02-01-01       1
3   2  01-01-01       0
like image 195
Scott Boston Avatar answered Apr 28 '26 21:04

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!