I wish to subtract some number of months from a datetime column. Each row has a different number of months to subtract. For example,
df = pd.DataFrame({
'timestamp': pd.date_range('2017-10-01', '2018-10-01', freq='m'),
'delta_in_months': [1, 4, 2, 5, 1, 3, 1, 5, 2, 4, 1, 3]
})
The outcome should look as so (the day rounding irrelevant, it could be 01 or 28/29/30/31, it was easier to type in 01),
timestamp delta_in_months new_timestamp
0 2017-10-31 1 2017-09-01
1 2017-11-30 4 2017-07-01
2 2017-12-31 2 2017-10-01
3 2018-01-31 5 2017-08-01
4 2018-02-28 1 2018-01-01
5 2018-03-31 3 2017-12-01
6 2018-04-30 1 2018-03-01
7 2018-05-31 5 2017-12-01
8 2018-06-30 2 2018-04-01
9 2018-07-31 4 2018-03-01
10 2018-08-31 1 2018-07-01
11 2018-09-30 3 2018-06-01
Bear in mind that this will be for a much larger dataframe.
I have tried,
months_delta = df.delta_in_months.apply(pd.tseries.offsets.MonthOffset)
df['new_timestamp'] = df.timestamp - months_delta
but this gave very unexpected results, with each row entry being a DatetimeIndex.