
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
Stack a Single Level Column with Pandas Stack
To stack a single-level column, use the datafrem.stack(). At first, let us import the required library −
import pandas as pd
Create a DataFrame with single-level column −
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b'])
Stack the DataFrame using the stack() method −
dataFrame.stack()
Example
Following is the complete code −
import pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b']) # DataFrame print"DataFrame...\n",dataFrame # stack print"\nStacking...\n",dataFrame.stack()
Output
This will produce the following output −
DataFrame... a b w 10 15 x 20 25 y 30 35 z 40 45 Stacking... w a 10 b 15 x a 20 b 25 y a 30 b 35 z a 40 b 45 dtype: int64
Advertisements