Martin
Martin

Reputation: 1475

Convert a numerical relative index (=months) to datetime

Given is a Pandas DataFrame with a numerical index representing the relative number of months:

df = pd.DataFrame(columns=['A', 'B'], index=np.arange(1,100))
df

    A   B
1   NaN NaN
2   NaN NaN
3   NaN NaN
... 

How can the index be converted to a DateTimeIndex by specifying a start date (e.g., 2018-11-01)?

magic_function(df, start='2018-11-01', delta='month')

           A  B
2018-11-01 NaN NaN
2018-12-01 NaN NaN
2019-01-01 NaN NaN
...

I would favor a general solution that also works with arbitrary deltas, e.g. daily or yearly series.

Upvotes: 1

Views: 102

Answers (2)

BENY
BENY

Reputation: 323226

Using date_range

idx=pd.date_range(start='2018-11-01',periods =len(df),freq='MS')
df.index=idx

Upvotes: 1

I'm not sure with Pandas, but with plain datetime can't you just do this?

import datetime start=datetime.date(2018,1,1) months = 15 adjusted = start.replace(year=start.year + int(months/12), month=months%12)

Upvotes: 0

Related Questions