Search code examples
pandastimedelta

How to calculate timedelta in dataframe column


I want to add a new column in a dataframe that show a new date in column which is date in b column add months in a column.

a b
3 2021-08-01
2 2021-07-01
5 2021-01-01
a b c
3 2021-08-01 2021-11-01
2 2021-07-01 2021-09-01
5 2021-01-01 2021-06-01

I have try

pd.to_datetime(df['b'] + timedelta(df ['a'])

But it doesn't work.


Solution

  • Let us do

    df['new'] = df.apply(lambda x: x['b'] + pd.offsets.MonthBegin(x['a']), axis=1)
    Out[194]: 
    0   2021-11-01
    1   2021-09-01
    2   2021-06-01
    dtype: datetime64[ns]