Pandas DataFrame | droplevel method
Start your free 7-days trial now!
Pandas DataFrame.droplevel(~)
method returns a new DataFrame with the specified column or index levels removed.
Parameters
1. level
link | int
or string
or list-like
The level(s) to remove. You can refer to the levels either by integer index or by their name.
2. axis
link | int
or string
| optional
Whether to remove levels from the column or the index:
Axis | Description |
---|---|
| Remove levels from the index. |
| Remove levels from the column. |
By default, axis=0
.
Return Value
A new DataFrame
with the specified column or index levels removed.
Examples
Dropping level from a multi-index row
Consider the following 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 remove the outer level from the index:
df.droplevel(0)
aalice 2bob 3cathy 4david 5eric 6
To remove the inner level from the index:
df.droplevel(1)
aA 2A 3A 4B 5B 6
Dropping levels from a multi-index column
Consider the following 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 drop the outer level from the column:
df.droplevel(0, axis=1)
alice bob cathy david eric0 2 3 4 5 6
To remove the inner level from the column:
df.droplevel(1, axis=1)
A A A B B0 2 3 4 5 6