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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With