I have a data frame with a column indicating the number of months. I would like to create a new column, starting from an initial date, let’s say 2015-01-01
and add all the months to this initial date. For example, if the month column has values [0, 1, 2, …,72]
, then I would like to have a column called Date of the form [2015-01-01,2015-02-01,2015-03-01,…]
.
How could I achieve this?
CodePudding user response:
Use offsets.DateOffset
and add to datetime
:
df = pd.DataFrame({'n': [0,1,2,72]})
start = '2015-01-01'
df['new'] = pd.to_datetime(start) df['n'].apply(lambda x: pd.offsets.DateOffset(months=x))
print (df)
n new
0 0 2015-01-01
1 1 2015-02-01
2 2 2015-03-01
3 72 2021-01-01