Sort MultiIndex at the requested level. This method is useful when dealing with MultiIndex objects, allowing for sorting at a specific level of the index. The function preserves the relative ordering of data within the same level while sorting the overall Mu
(
self,
level: IndexLabel = 0,
ascending: bool | list[bool] = True,
sort_remaining: bool = True,
na_position: str = "first",
)
| 3065 | ] |
| 3066 | |
| 3067 | def sortlevel( |
| 3068 | self, |
| 3069 | level: IndexLabel = 0, |
| 3070 | ascending: bool | list[bool] = True, |
| 3071 | sort_remaining: bool = True, |
| 3072 | na_position: str = "first", |
| 3073 | ) -> tuple[MultiIndex, npt.NDArray[np.intp]]: |
| 3074 | """ |
| 3075 | Sort MultiIndex at the requested level. |
| 3076 | |
| 3077 | This method is useful when dealing with MultiIndex objects, allowing for |
| 3078 | sorting at a specific level of the index. The function preserves the |
| 3079 | relative ordering of data within the same level while sorting |
| 3080 | the overall MultiIndex. The method provides flexibility with the `ascending` |
| 3081 | parameter to define the sort order and with the `sort_remaining` parameter to |
| 3082 | control whether the remaining levels should also be sorted. Sorting a |
| 3083 | MultiIndex can be crucial when performing operations that require ordered |
| 3084 | indices, such as grouping or merging datasets. The `na_position` argument is |
| 3085 | important in handling missing values consistently across different levels. |
| 3086 | |
| 3087 | Parameters |
| 3088 | ---------- |
| 3089 | level : list-like, int or str, default 0 |
| 3090 | If a string is given, must be a name of the level. |
| 3091 | If list-like must be names or ints of levels. |
| 3092 | ascending : bool, default True |
| 3093 | False to sort in descending order. |
| 3094 | Can also be a list to specify a directed ordering. |
| 3095 | sort_remaining : bool, default True |
| 3096 | If True, sorts by the remaining levels after sorting by the specified |
| 3097 | `level`. |
| 3098 | na_position : {'first' or 'last'}, default 'first' |
| 3099 | Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at |
| 3100 | the end. |
| 3101 | |
| 3102 | .. versionadded:: 2.1.0 |
| 3103 | |
| 3104 | Returns |
| 3105 | ------- |
| 3106 | sorted_index : pd.MultiIndex |
| 3107 | Resulting index. |
| 3108 | indexer : np.ndarray[np.intp] |
| 3109 | Indices of output values in original index. |
| 3110 | |
| 3111 | See Also |
| 3112 | -------- |
| 3113 | MultiIndex : A multi-level, or hierarchical, index object for pandas objects. |
| 3114 | Index.sort_values : Sort Index values. |
| 3115 | DataFrame.sort_index : Sort DataFrame by the index. |
| 3116 | Series.sort_index : Sort Series by the index. |
| 3117 | |
| 3118 | Examples |
| 3119 | -------- |
| 3120 | >>> mi = pd.MultiIndex.from_arrays([[0, 0], [2, 1]]) |
| 3121 | >>> mi |
| 3122 | MultiIndex([(0, 2), |
| 3123 | (0, 1)], |
| 3124 | ) |