In a dataframe df containing the columns person_id (int), dates (datetimes), and is_hosp (boolean), I need to find out for each date of each person_id if is_hosp is true in the next 15 days following the date of the row.
EDIT:
Following pertinent comments to the orginal question, I should specify that the dates of observations for each row / person_id are not always consecutive (ie a person_id can have an observation on the 01/01/2018 followed by the next observation on the 08/01/2018).
I have written the code below but it is very slow.
To replicate the issue, here is a fake dataframe of the same format as the dataframe I am working on:
import pandas as pd
import datetime as dt
import numpy as np
count_unique_person = 10
dates = pd.date_range(dt.datetime(2019, 1, 1), dt.datetime(2021, 1, 1))
dates = dates.to_pydatetime().tolist()
person_id = [i for i in range(1, count_unique_person + 1) for _ in range(len(dates))]
dates = dates * count_unique_person
sample_arr = [True, False]
col_to_check = np.random.choice(sample_arr, size = len(dates))
df = pd.DataFrame()
df['person_id'] = person_id
df['dates'] = dates
df['is_hosp'] = col_to_check
Here is how I have implemented the check (column is_inh_15d), but it takes too long to run (my original dataframe contains a million rows):
is_inh = []
is_inh_idx = []
for each_p in np.unique(df['person_id'].values):
t_df = df[df['person_id'] == each_p].copy()
for index, e_row in t_df.iterrows():
s_dt = e_row['dates']
e_dt = s_dt + dt.timedelta(days = 15)
t_df2 = t_df[(t_df['dates'] >= s_dt) & (t_df['dates'] <= e_dt)]
is_inh.append(np.any(t_df2['is_hosp'] == True))
is_inh_idx.append(index)
h_15d_df = pd.DataFrame()
h_15d_df['is_inh_15d'] = is_inh
h_15d_df['is_inh_idx'] = is_inh_idx
h_15d_df.set_index('is_inh_idx', inplace = True)
df = df.join(h_15d_df)
I don't see how to vectorize the logic of checking each of the next 15 days for each row to see if "is_hosp" is True.
Could someone please advise?