简体   繁体   中英

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' (eg 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'),

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM