Pandas Series: droplevel() function
Series-droplevel() function
The droplevel() function is used to return DataFrame with requested index / column level(s) removed.
Syntax:
Series.droplevel(self, level, axis=0)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
level | If a string is given, must be the name of a level If list-like, elements must be names or positional indexes of levels. | int, str, or list-like | Required |
axis | {0 or ‘index’, 1 or ‘columns’} Default Value: 0 |
Required |
Returns: DataFrame.droplevel()
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame([
[2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11, 12, 13]
]).set_index([0, 1]).rename_axis(['p', 'q'])
df.columns = pd.MultiIndex.from_tuples([
('r', 't'), ('s', 'v')
], names=['level_1', 'level_2'])
df
Output:
level_1 r s level_2 t v p q 2 3 4 5 6 7 8 9 10 11 12 13
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame([
[2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11, 12, 13]
]).set_index([0, 1]).rename_axis(['p', 'q'])
df.columns = pd.MultiIndex.from_tuples([
('r', 't'), ('s', 'v')
], names=['level_1', 'level_2'])
df.droplevel('p')
Output:
level_1 r s level_2 t v q 3 4 5 7 8 9 11 12 13
Python-Pandas Code:
import numpy as np
import pandas as pd
df = pd.DataFrame([
[2, 3, 4, 5],
[6, 7, 8, 9],
[10, 11, 12, 13]
]).set_index([0, 1]).rename_axis(['p', 'q'])
df.columns = pd.MultiIndex.from_tuples([
('r', 't'), ('s', 'v')
], names=['level_1', 'level_2'])
df.droplevel('level_2', axis=1)
Output:
level_1 r s p q 2 3 4 5 6 7 8 9 10 11 12 13
Previous: Remove series with specified index labels
Next: Remove Pandas series with duplicate values
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics