Python - Stacking a multi-level column in a Pandas DataFrame

PythonServer Side ProgrammingProgramming

To stack a multi-level column, use the stack() method. At first, import the required library −

import pandas as pd

Create a multi-level column −

items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),('Maths', 'Applied Mathematics')])

Now, create a DataFrame and set multi-level columns we set above −

dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)

Stack the multi-level column −

dataframe.stack()

Example

Following is the complete code −

import pandas as pd

# multi-level columns
items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),
('Maths', 'Applied Mathematics')])

# creating a DataFrame
dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)

# DataFrame
print"DataFrame...\n",dataFrame

# stack multi-level columns
print"\nStacking...\n",dataFrame.stack()

Output

This will produce the following output −

DataFrame...
           Maths
      Mental Maths  Discrete Mathematics  Applied Mathematics
John            67                    86                   78
Tom             56                    92                   97
Henry           92                    95                   91

Stacking...
                            Maths
John   Applied Mathematics     78
       Discrete Mathematics    86
       Mental Maths            67
Tom    Applied Mathematics     97
       Discrete Mathematics    92
       Mental Maths            56
Henry  Applied Mathematics     91
       Discrete Mathematics    95
       Mental Maths            92
raja
Published on 22-Sep-2021 12:40:57
Advertisements