Set new levels on MultiIndex. Defaults to returning new index. The `set_levels` method provides a flexible way to change the levels of a `MultiIndex`. This is particularly useful when you need to update the index structure of your DataFrame without altering the data
(
self, levels, *, level=None, verify_integrity: bool = True
)
| 928 | self._reset_cache() |
| 929 | |
| 930 | def set_levels( |
| 931 | self, levels, *, level=None, verify_integrity: bool = True |
| 932 | ) -> MultiIndex: |
| 933 | """ |
| 934 | Set new levels on MultiIndex. Defaults to returning new index. |
| 935 | |
| 936 | The `set_levels` method provides a flexible way to change the levels of a |
| 937 | `MultiIndex`. This is particularly useful when you need to update the |
| 938 | index structure of your DataFrame without altering the data. The method |
| 939 | returns a new `MultiIndex` unless the operation is performed in-place, |
| 940 | ensuring that the original index remains unchanged unless explicitly |
| 941 | modified. |
| 942 | |
| 943 | The method checks the integrity of the new levels against the existing |
| 944 | codes by default, but this can be disabled if you are confident that |
| 945 | your levels are consistent with the underlying data. This can be useful |
| 946 | when you want to perform optimizations or make specific adjustments to |
| 947 | the index levels that do not strictly adhere to the original structure. |
| 948 | |
| 949 | Parameters |
| 950 | ---------- |
| 951 | levels : sequence or list of sequence |
| 952 | New level(s) to apply. |
| 953 | level : int, level name, or sequence of int/level names (default None) |
| 954 | Level(s) to set (None for all levels). |
| 955 | verify_integrity : bool, default True |
| 956 | If True, checks that levels and codes are compatible. |
| 957 | |
| 958 | Returns |
| 959 | ------- |
| 960 | MultiIndex |
| 961 | A new `MultiIndex` with the updated levels. |
| 962 | |
| 963 | See Also |
| 964 | -------- |
| 965 | MultiIndex.set_codes : Set new codes on the existing `MultiIndex`. |
| 966 | MultiIndex.remove_unused_levels : Create new MultiIndex from current that |
| 967 | removes unused levels. |
| 968 | Index.set_names : Set Index or MultiIndex name. |
| 969 | |
| 970 | Examples |
| 971 | -------- |
| 972 | >>> idx = pd.MultiIndex.from_tuples( |
| 973 | ... [ |
| 974 | ... (1, "one"), |
| 975 | ... (1, "two"), |
| 976 | ... (2, "one"), |
| 977 | ... (2, "two"), |
| 978 | ... (3, "one"), |
| 979 | ... (3, "two"), |
| 980 | ... ], |
| 981 | ... names=["foo", "bar"], |
| 982 | ... ) |
| 983 | >>> idx |
| 984 | MultiIndex([(1, 'one'), |
| 985 | (1, 'two'), |
| 986 | (2, 'one'), |
| 987 | (2, 'two'), |