Luca Monno
Luca Monno

Reputation: 880

Offset pandas datetime series by months

I've a pandas df with dates and index like the following

df = pd.DataFrame({'dates': ['2021-09-30','2021-12-31','2021-12-31'],
            'idx':[1,2,3]})

I'd like to move the dates bu n months using the idx column.

I converted the column dates using the datetime format:

df['dates'] = pd.to_datetime(df['dates'])

And then I tried to use some function like MonthEnd or DateOffset from pandas.tseries.offsets but they only work with an integer (and not a list). Do you have any suggestions?

The final result should be the following:

df = pd.DataFrame({'newdates': ['2021-10-31','2022-02-28','2022-03-31']})

Thank you

Upvotes: 1

Views: 418

Answers (3)

akuiper
akuiper

Reputation: 214967

With DateOffset / MonthEnd, you can try this:

from pandas.tseries.offsets import DateOffset, MonthEnd
df.dates + df.idx.map(lambda m: DateOffset(months=m)) + MonthEnd(0)

0   2021-10-31
1   2022-02-28
2   2022-03-31
dtype: datetime64[ns]

Upvotes: 1

Jayvee
Jayvee

Reputation: 10875

Using @Psidom method just adjusting the month end date:

from pandas.tseries.offsets import DateOffset

df['new_dates']=(df.dates+DateOffset(days=1) + df.idx.map(lambda m: DateOffset(months=m)))-DateOffset(days=1)



    dates   idx     new_dates
0   2021-09-30  1   2021-10-31
1   2021-12-31  2   2022-02-28
2   2021-12-31  3   2022-03-31

Upvotes: 1

Yusuf Ertas
Yusuf Ertas

Reputation: 306

from dateutil.relativedelta import relativedelta

df['new_dates'] = df.apply(lambda x: x['dates'] + relativedelta(month=x['idx']), axis=1)

Upvotes: 0

Related Questions