[英]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.我有一个带有以下 MultiIndex 的数据框,我需要用一个索引(称为“日期”)替换该索引,该索引应该由天和小时/分钟组成。
Currently I'm using df.reset_index(level=[0,1])目前我正在使用 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).我相信我现在需要从生成的“日期”(datetime64)和“分钟”(例如 09:30)重新创建索引。
Is the simplest approach to convert that datetime object to a string, and then use to_datetime()?将该日期时间对象转换为字符串,然后使用 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.重置索引为您提供了一个“正常”索引,但您需要一个 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.它甚至可能足够聪明,可以直接应用于 multiIndex ...
to_datetime()
非常聪明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.