Skip to content

DOC add example to reorder levels #42935

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 23, 2021
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6790,7 +6790,6 @@ def swaplevel(self, i: Axis = -2, j: Axis = -1, axis: Axis = 0) -> DataFrame:
assert isinstance(result.columns, MultiIndex)
result.columns = result.columns.swaplevel(i, j)
return result

def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame:
"""
Rearrange index levels using input order. May not drop or duplicate levels.
Expand All @@ -6806,6 +6805,32 @@ def reorder_levels(self, order: Sequence[Axis], axis: Axis = 0) -> DataFrame:
Returns
-------
DataFrame

Examples
--------
>>> data={'class':['Mammals','Mammals','Reptiles','Reptiles'
,'Amphibians','Amphibians'],
'diet':['Omnivore','Carnivore','Carnivore','Herbivore','Omnivore','Herbivore'],
'species':['Humans','Dogs','Snakes','Iguanas','Frogs','Aquatic Salamanders']
}
>>> df=pd.DataFrame(data,columns=['class','diet','species'])
>>> df.set_index(['class','diet'],drop=True)
>>> df.reorder_levels(["diet", "class"])
diet class species
Omnivore Mammals Humans
Carnivore Mammals Dogs
Reptiles Snakes
Herbivore Reptiles Iguanas
Omnivore Amphibians Frogs
Herbivore Amphibians Aquatic Salamanders
>>> df.reorder_levels(["class","diet"])
class diet species
Mammals Omnivore Humans
Carnivore Dogs
Reptiles Carnivore Snakes
Herbivore Iguanas
Amphibians Omnivore Frogs
Herbivore Aquatic Salamanders
"""
axis = self._get_axis_number(axis)
if not isinstance(self._get_axis(axis), MultiIndex): # pragma: no cover
Expand Down