I'm looking for help with this simultaneous group-by / row-on-row difference problem in Pandas. The problem is exactly as stated here for R: How to calculate time difference between datetimes, for each group (student-contract)?
I have data like this:
# USER_ID CONTRACT_REF SUBMISSION_DATE
1 1 A 20/6 01:00
2 1 A 20/6 02:00
3 1 B 20/6 03:00
4 4 A 20/6 04:00
5 5 A 20/6 05:00
6 5 B 20/6 06:00
7 7 A 20/6 07:00
8 7 B 20/6 08:00
9 7 B 20/6 09:30
10 7 B 20/6 10:00
I want to calculate the time difference from the previous submission for each unique USER_ID - CONTRACT_REF pair.
Note: each USER_ID - CONTRACT_REF pair has to have a zero (or null) for its first appearance.
So the output should look as follows:
# USER_ID CONTRACT_REF SUBMISSION_DATE TIME_DIFFERENCE
1 1 A 20/6 01:00 0
2 1 A 20/6 02:00 1
3 1 B 20/6 03:00 0
4 4 A 20/6 04:00 0
5 5 A 20/6 05:00 0
6 5 B 20/6 06:00 0
7 7 A 20/6 07:00 0
8 7 A 20/6 08:00 1
9 7 A 20/6 09:30 1.5
10 7 B 20/6 10:00 0
I'm currently moving to Pandas from R, and while I find the syntax refreshing, I'm a bit stumped when it comes to complex functions on dataframes.
Thanks in advance for any tips!