joshlk
joshlk

Reputation: 1651

Add a number of days to a date/datetime (Pandas/Numpy)

In Pandas, I would like to add a number of days to a date/datetime (two columns).

Example:

dates = pd.Series(pd.date_range("20180101 00:00", "20180104 00:00"))

0   2018-01-01
1   2018-01-02
2   2018-01-03
3   2018-01-04
dtype: datetime64[ns]

days = pd.Series(np.arange(4)).astype('float')

0    0.0
1    1.0
2    2.0
3    3.0
dtype: float64

What I have tried (and the associated error I get):

dates + days

TypeError: cannot operate on a series without a rhs of a series/ndarray of type datetime64[ns] or a timedelta

dates + days.astype('int')

TypeError: incompatible type for a datetime/timedelta operation [__add__]

dates + pd.DateOffset(days=days)

TypeError: DatetimeIndex cannot perform the operation +

dates + np.timedelta64(days.values)

ValueError: Could not convert object to NumPy timedelta

dates + pd.offsets.Day(days)

TypeError: cannot convert the series to

dates + pd.datetools.timedelta(days=days)

TypeError: unsupported type for timedelta days component: Series

Upvotes: 1

Views: 3775

Answers (1)

joshlk
joshlk

Reputation: 1651

At last I have found two methods!:

dates + pd.to_timedelta(days, unit='D') 

or

dates + pd.TimedeltaIndex(days, unit='D')

Which both produce:

0   2018-01-01
1   2018-01-03
2   2018-01-05
3   2018-01-07
dtype: datetime64[ns]

(It took ages to find the relevant documentation: https://pandas.pydata.org/pandas-docs/stable/timedeltas.html#to-timedelta)

Upvotes: 5

Related Questions