Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Stacking a multi-level column in a Pandas DataFrame
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 92Advertisements