15 KiB
Exercise window functions: compute the cumulative number of cases across time, per diet group¶
The variable toevent
contains the time that patients where followed up. We want to calculate the number of events as a function of the follow-up time, separatedely for each diet group. We expect that, if the mediterranean diet has an effect, then over time there will be more cases appearing on the control group in comparison to the other diet groups.
Here is how to proceed:
- Use a window function to compute the cumulative number of events for each diet group separatedly. As we are interested in the follow-up time, you need to sort the events by the follow-up time first (
toevent
), and then calculate the cumulative sum of events, separatedely per group. - Add the result as a new column called
'cumulative_event_count'
With your new awesome vectorization skills, these two steps should take only one line!
When ready, execute the code at the end, which has already code that creates a visualiation with the cumulative number of events per group, as a function of the time of follow-up.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
Load patient data¶
df = pd.read_csv('processed_data_predimed.csv')
df['event'] = df['event'].map({'Yes': 1, 'No': 0})
df
# calculate cumulative number of cases across time, independently for each group
# your code here:
If you do it right, the following code will create a visualization as shown in the slides. Uncomment it
#sns.lineplot(data=df.sort_values('toevent'), x='toevent', y='cumulative_event_count', hue='group')
#plt.ylabel('Cumulative events')
#plt.xlabel('Years of follow up (variable `toevent`)')
#sns.despine()
Optional exercise¶
Redo the plot but with the cummulative percentage of cases. For that you need to divide the cummulative count by the total number of cases in each group.
# your code here: