Pandas Timedelta in months

Update for pandas 0.24.0:

Since 0.24.0 has changed the api to return MonthEnd object from period subtraction, you could do some manual calculation as follows to get the whole month difference:

12 * (df.today.dt.year - df.date.dt.year) + (df.today.dt.month - df.date.dt.month)

# 0    2
# 1    1
# dtype: int64

Wrap in a function:

def month_diff(a, b):
    return 12 * (a.dt.year - b.dt.year) + (a.dt.month - b.dt.month)

month_diff(df.today, df.date)
# 0    2
# 1    1
# dtype: int64

Prior to pandas 0.24.0. You can round the date to Month with to_period() and then subtract the result:

df['elapased_months'] = df.today.dt.to_period('M') - df.date.dt.to_period('M')

df
#         date       today  elapased_months
#0  2016-10-11  2016-12-02                2
#1  2016-11-01  2016-12-02                1

Leave a Comment

tech