Pandas
keyboard_arrow_down 655 guides
chevron_leftSorting and Restructuring DataFrames
check_circle
Mark as learned thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment auto_stories Bi-column layout
settings
Pandas DataFrame | swaplevel method
schedule Aug 12, 2023
Last updated local_offer
Tags Python●Pandas
tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
Start your free 7-days trial now!
Pandas DataFrame.swaplevel(~)
method swaps two levels of a multi-index DataFrame.
Parameters
1. i
link | int
or string
The level to swap. You can refer to the levels either by integer index or by their name.
2. j
link | int
or string
The other level to swap with.
3. axis
link | int
or string
| optional
Whether to swap levels of index or columns:
Axis | Description |
---|---|
| Swap levels of the index. |
| Swap levels of the column. |
By default, axis=0
.
Return Value
A new DataFrame
with a pair of levels swapped.
Examples
Swapping a pair of index levels
Consider the following multi-index DataFrame:
index = [("A", "alice"), ("A", "bob"),("A", "cathy"), ("B", "david"),("B", "eric")]multi_index = pd.MultiIndex.from_tuples(index)df = pd.DataFrame({"a":[2,3,4,5,6]}, index=multi_index)df
aA alice 2 bob 3 cathy 4B david 5 eric 6
To swap the two levels:
df.swaplevel(0,1)
aalice A 2bob A 3cathy A 4david B 5eric B 6
Here, we are swapping the inner-most level (1
) with the outer-most level (0
).
Swapping a pair of column levels
Consider the following multi-level column DataFrame:
index = [("A", "alice"), ("A", "bob"),("A", "cathy"), ("B", "david"),("B", "eric")]multi_index = pd.MultiIndex.from_tuples(index)df = pd.DataFrame([[2,3,4,5,6]], columns=multi_index)df
A B alice bob cathy david eric0 2 3 4 5 6
To swap the ordering of the column levels, set axis=1
like so:
df.swaplevel(1, 0, axis=1)
alice bob cathy david eric A A A B B0 2 3 4 5 6
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
Official Pandas Documentation
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.swaplevel.html
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!