@@ -843,6 +843,53 @@ def size(self) -> int:
843
843
844
844
@cache_readonly
845
845
def levels (self ) -> FrozenList :
846
+ """
847
+ Levels of the MultiIndex.
848
+
849
+ Levels refer to the different hierarchical levels or layers in a MultiIndex.
850
+ In a MultiIndex, each level represents a distinct dimension or category of
851
+ the index.
852
+
853
+ To access the levels, you can use the levels attribute of the MultiIndex,
854
+ which returns a tuple of Index objects. Each Index object represents a
855
+ level in the MultiIndex and contains the unique values found in that
856
+ specific level.
857
+
858
+ If a MultiIndex is created with levels A, B, C, and the DataFrame using
859
+ it filters out all rows of the level C, MultiIndex.levels will still
860
+ return A, B, C.
861
+
862
+ Examples
863
+ --------
864
+ >>> index = pd.MultiIndex.from_product([['mammal'],
865
+ ... ('goat', 'human', 'cat', 'dog')], names=['Category', 'Animals'])
866
+ >>> leg_num = pd.DataFrame(data=(4, 2, 4, 4), index=index, columns=['Legs'])
867
+ >>> leg_num
868
+ Legs
869
+ Category Animals
870
+ mammal goat 4
871
+ human 2
872
+ cat 4
873
+ dog 4
874
+
875
+ >>> leg_num.index.levels
876
+ FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']])
877
+
878
+ MultiIndex levels will not change even if the DataFrame using the MultiIndex
879
+ does not contain all them anymore.
880
+ See how "human" is not in the DataFrame, but it is still in levels:
881
+
882
+ >>> large_leg_num = leg_num[leg_num.Legs > 2]
883
+ >>> large_leg_num
884
+ Legs
885
+ Category Animals
886
+ mammal goat 4
887
+ cat 4
888
+ dog 4
889
+
890
+ >>> large_leg_num.index.levels
891
+ FrozenList([['mammal'], ['cat', 'dog', 'goat', 'human']])
892
+ """
846
893
# Use cache_readonly to ensure that self.get_locs doesn't repeatedly
847
894
# create new IndexEngine
848
895
# https://github.com/pandas-dev/pandas/issues/31648
0 commit comments