我想为数据帧创建一个 lexsort-深度 7 的多重索引。但是,在索引的几个深度上我只有相同的值。 Pandas 多索引构造函数排除具有相同值的那些。有什么办法可以保留它们吗?
例如:
import pandas as pd
labels =
[(0, 0, 5, 0, 1, 0, 0), (0, 0, 5, 0, 1, 0, 0), (0, 0, 5, 0, 1, 0, 0),
(0, 0, 5, 0, 2, 0, 0), (0, 0, 5, 0, 2, 0, 0), (0, 0, 5, 0, 2, 0, 0),
(0, 0, 5, 0, 3, 0, 0), (0, 0, 5, 0, 3, 0, 0), (0, 0, 5, 0, 3, 0, 0),
(0, 0, 5, 0, 0, 0, 0), (0, 0, 5, 0, 0, 0, 0), (0, 0, 5, 0, 0, 0, 0),
(0, 0, 4, 0, 1, 0, 0), (0, 0, 4, 0, 1, 0, 0), (0, 0, 4, 0, 1, 0, 0),
(0, 0, 4, 0, 2, 0, 0), (0, 0, 4, 0, 2, 0, 0), (0, 0, 4, 0, 2, 0, 0),
(0, 0, 4, 0, 3, 0, 0), (0, 0, 4, 0, 3, 0, 0)]
index = pd.MultiIndex.from_tuples(labels)
index.lexsort_depth
>>> 2 # what I want is 7 here
最佳答案
您需要首先对 MI 进行排序,以使其具有完整的词法排序深度:
In [11]: index = index.order()
In [12]: index.lexsort_depth
Out[12]: 7
目前它的排序还没有超过第二级(其中 5 在 4 之前)。
关于python - pandas 多索引退化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25725055/