如何将multiindex转换为datetimeindex? 没有reindex

问题描述

我需要使用“ modin”数据帧,该数据帧不能与multindexes配合使用(有一点我要做 df.reindex(idx),其中idx是多级索引), 所以: 如何将多索引转换为单索引? (将两个级别合并在一起)

最小样本:


import pandas as pd
idx = pd.DatetimeIndex(['2019-07-17 22:43:00','2019-07-17 22:44:00','2019-07-17 22:45:00','2019-07-17 22:46:00','2019-07-17 22:47:00','2019-07-17 22:48:00','2019-07-17 22:49:00','2019-07-17 22:50:00','2019-07-17 22:51:00','2019-07-17 22:52:00','2019-07-23 22:33:00','2019-07-23 22:34:00','2019-07-23 22:35:00','2019-07-23 22:36:00','2019-07-23 22:37:00','2019-07-23 22:38:00','2019-07-23 22:39:00','2019-07-23 22:40:00','2019-07-23 22:41:00','2019-07-23 22:42:00'] ) 

idx = pd.MultiIndex.from_tuples(zip( idx.date,idx.time))

dates_new   =  idx.get_level_values(0).unique()  
times_new =  idx.get_level_values(1).unique()

idx = pd.MultiIndex.from_product([dates_new,times_new]) 
idx = pd.DatetimeIndex(idx)
print(idx)

以下方法有效,但是有什么方法可以加快速度(在大型数据集上)?

[datetime.datetime.combine(date,time) for date,time in idx.values]

解决方法

您的问题是从DateTimeIndex开始的,您想查找DateTime的所有组合并将其转换为新的DateTimeIndex

我不会使用.time访问权限,因为它提供了一个datetime对象,该对象不能与Pandas很好地配合使用。相反,让我们尝试:

dates_new = set(idx.normalize())
times_new = set(idx - idx.normalize())

from itertools import product
new_idx = pd.DatetimeIndex([x+y for x,y in product(dates_new,times_new)])

输出:

DatetimeIndex(['2019-07-23 22:36:00','2019-07-23 22:41:00','2019-07-23 22:50:00','2019-07-23 22:40:00','2019-07-23 22:45:00','2019-07-23 22:51:00','2019-07-23 22:33:00','2019-07-23 22:42:00','2019-07-23 22:37:00','2019-07-23 22:46:00','2019-07-23 22:43:00','2019-07-23 22:52:00','2019-07-23 22:34:00','2019-07-23 22:47:00','2019-07-23 22:38:00','2019-07-23 22:35:00','2019-07-23 22:44:00','2019-07-23 22:49:00','2019-07-23 22:39:00','2019-07-23 22:48:00','2019-07-17 22:36:00','2019-07-17 22:41:00','2019-07-17 22:50:00','2019-07-17 22:40:00','2019-07-17 22:45:00','2019-07-17 22:51:00','2019-07-17 22:33:00','2019-07-17 22:42:00','2019-07-17 22:37:00','2019-07-17 22:46:00','2019-07-17 22:43:00','2019-07-17 22:52:00','2019-07-17 22:34:00','2019-07-17 22:47:00','2019-07-17 22:38:00','2019-07-17 22:35:00','2019-07-17 22:44:00','2019-07-17 22:49:00','2019-07-17 22:39:00','2019-07-17 22:48:00'],dtype='datetime64[ns]',freq=None)