I want to calculate the number of days from consecutive periods.
In the df below I have four columns:
- id; representing a person.
- period; a number where the lowest is the first period and the highest the latest.
- in_date; date when the period starts.
- out_date; date when the period ends.
I want to build a generic function that performs the following:
calculate the number of days of consecutive periods. Two periods are considered consecutive if the number of days between them is less than 90.
I want only to calculate the number of days if the last period for an id has an out_date in 2013. If the last period has an 'out_date' of 2014 or 2012 I want to disregard that ID.
I want to include the days between periods in the result variable.
My problem is, as I'm fairly new to Python, I can't seam to come up with a good idea how to calculate the days between periods and classify a consecutive period. Any help would be much appreciated.
import pandas as pd
import numpy as np
import datetime
data = {'id':[1, 1, 1, 2, 2, 2, 2, 3, 3, 3],
'period':[1, 2, 3, 1, 3, 5, 6, 2, 3, 4],
'in_date': ['2011-02-15','2011-11-10','2012-10-13',
'2010-04-03','2012-02-17','2012-08-15','2014-01-04','2010-06-01','2012-03-29','2012-09-12'],
'out_date': ['2011-05-21','2012-10-11','2013-10-25',
'2012-02-16','2012-02-19','2013-11-23','2014-12-18','2011-08-21','2012-09-11','2013-01-10']}
df = pd.DataFrame(data)
df['in_date'] = pd.to_datetime(df['in_date'])
df['out_date'] = pd.to_datetime(df['out_date'])
df['n_days'] = df['out_date'] - df['in_date']
Expected output:
