Get the value from the previous datetime minute per user
Original Dataframe
I have a Dataframe structured like this:
User Datetime Hits
0 A 2021-03-10 15:25:26 10
1 A 2021-03-10 15:25:52 10
2 A 2021-03-10 15:26:09 12
3 A 2021-03-10 15:26:12 12
4 B 2021-03-10 15:25:32 6
5 A 2021-03-10 15:27:39 15
Goal
My goal is to obtain the difference (Delta) per User between the current 'Hits' value and the value from last minute.
For every specific datetime minute, the 'Hits' value per user is the same, as this value is the result from a value_counts() operation for this specific minute.
Hence, multiple similar 'Hits' values per user can be present per minute.
Methods tried
I have succeeded using .apply in combination with a rather complex function, but the problem is that this method is too slow for the size of the original dataframe.
More specifically I am looking for a faster method, ideally without custom functions.
Target Dataframe
My target Dataframe will look like this:
User Datetime Hits Delta
0 A 2021-03-10 15:25:26 10 <NA>
1 A 2021-03-10 15:25:52 10 <NA>
2 A 2021-03-10 15:26:09 12 2
3 A 2021-03-10 15:26:12 12 2
4 B 2021-03-10 15:25:32 6 <NA>
5 A 2021-03-10 15:27:39 15 3
Code for Dataframe
d = {'User': ['A', 'A', 'A', 'A', 'B','A'],
'Datetime': ['2021-03-10 15:25:26', '2021-03-10 15:25:52', '2021-03-10 15:26:09', '2021-03-10 15:26:12', '2021-03-10 15:25:32', '2021-03-10 15:27:39'],
'Hits': [10,10,12,12,6,15],
'Delta': pd.NA}
df = pd.DataFrame(data=d)
df