David
David

Reputation: 605

Pandas Dataframe convert MultiIndex to single datetimeindex

I have a dataframe with the following MultiIndex and I need to replace that index with a single index (called 'date') which should be composed of both the day and the hours/minutes.

Currently I'm using df.reset_index(level=[0,1])

I believe I now need to re-create the index from the resulting 'date' (datetime64) and 'minute' (e.g. 09:30).

Is the simplest approach to convert that datetime object to a string, and then use to_datetime()?

df.index
MultiIndex([('2020-10-08', '09:30'),
            ('2020-10-08', '09:31'),
            ('2020-10-08', '09:32'),
            ('2020-10-08', '09:33'),
            ('2020-10-08', '09:34'),
            ('2020-10-08', '09:35'),

Upvotes: 0

Views: 466

Answers (1)

noah
noah

Reputation: 2786

Reset index is giving you a "normal" index but you need a DatetimeIndex. Just convert it after resetting:

df.index = pd.to_datetime(df.index)

It might even be smart enough to apply directly to the multiIndex... to_datetime() is pretty smart.

Upvotes: 1

Related Questions