Update for pandas 0.24.0 :
Since version 0.24.0 changed the API for returning a MonthEnd object from subtracting a period, you can perform some manual calculations as follows to get the difference for the whole month:
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 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
Before the panda 0.24.0. You can round the date to a 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
source
share