I have a dataframe that looks something like this:
ID | Category | Site | Task Completed |
---|---|---|---|
1 | A | X | 1/2/22 12:00:00AM |
1 | A | X | 1/3/22 12:00:00AM |
1 | A | X | 1/1/22 12:00:00AM |
1 | A | X | 1/2/22 1:00:00AM |
1 | B | Y | 1/1/22 1:00:00AM |
2 | A | Z | 1/2/22 12:00:00AM |
2 | A | Z | 1/1/22 12:00:00AM |
As you can see, there can be multiple task completed dates for a ID/Category/Site combo.
What I want to find is the time difference (in days) between the first (min) Task Completed date and the last (max) task completed date for every ID/Category/Site combination within the dataset. The intended result would look something like this:
ID | Category | Site | Time Difference |
---|---|---|---|
1 | A | X | 2 |
1 | B | Y | 0 |
2 | A | Z | 1 |
So far, I know that I have to change the 'task_completed' field to datetime and use groupby for each field which looks something like this:
df = pd.DataFrame(
[[1,'A','X','1/2/22 12:00:00AM'],
[1,'A','X','1/3/22 12:00:00AM'],
[1,'A','X','1/1/22 12:00:00AM'],
[1,'A','X','1/2/22 1:00:00AM'],
[1,'B','Y','1/1/22 1:00:00AM'],
[2,'A','Z','1/2/22 12:00:00AM'],
[2,'A','Z','1/1/22 12:00:00AM'],
columns=['ID', 'Category', 'Site', 'Task Completed'])
df['task_completed'] = pd.to_datetime(df['task_completed'])
res = df.sort_values('task_completed').groupby(['id','site','category']).first()
But I'm not sure how to get the max then subtract to get the intended result.