ANALYSIS TOOL BOX

Data Processing

AddTPeriodColumn

Calculate elapsed time periods from the earliest date in a DataFrame.

data-processingcleaningtransformationwrangling

Introduction

Cohort and longitudinal analyses hinge on a common question: how much time has elapsed since a baseline, not what the raw calendar date is. AddTPeriodColumn answers "how many days, weeks, months, or years have passed since the earliest date in this dataset?" by creating a normalized time index starting at 0, letting you compare trajectories across cohorts, patients, or customers that started on different dates. Reach for it when the analytic question is about progression from a starting point — retention curves, treatment timelines, customer lifetime patterns — rather than absolute dates.

Teaching Note

The function is particularly useful for:

  • Cohort analysis and retention studies
  • Time series modeling and forecasting
  • Tracking progression over time from a baseline
  • Normalizing dates across different starting points
  • Panel data analysis with time-based indexing
  • Event study analysis in finance and economics
  • Customer lifetime value calculations

Parameters

ParameterTypeDefaultDescription
dataframerequiredA pandas DataFrame containing at least one column with date or datetime values.
date_column_namerequiredName of the column containing date values from which to calculate time periods. The column will be converted to datetime format if not already.
t_period_interval'days'Unit of time for measuring elapsed periods. Must be one of: 'days', 'weeks', 'months', or 'years'.
t_period_column_nameNoneCustom name for the new T-period column. If None, the column will be automatically named 'T Period in {interval}'.

Returns

The input DataFrame with an additional column containing the T-period values — the number of complete intervals since the earliest date in the dataset. The earliest date(s) have a T-period value of 0.

Example

python
from analysistoolbox.data_processing import AddTPeriodColumn
import pandas as pd

# Calculate days since first event for user activity data
activity = pd.DataFrame({
    'user_id': [1, 1, 1, 2, 2],
    'event_date': ['2023-01-01', '2023-01-05', '2023-01-10', '2023-01-01', '2023-01-08']
})
activity = AddTPeriodColumn(activity, 'event_date', t_period_interval='days')
# Adds 'T Period in days': [0, 4, 9, 0, 7] - days since earliest date (2023-01-01)