Book Image

Learning Pandas

By : Michael Heydt
Book Image

Learning Pandas

By: Michael Heydt

Overview of this book

Table of Contents (19 chapters)
Learning pandas
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Stacking and unstacking


Similar to the pivot function are the .stack() and .unstack() methods that are part of both Series and DataFrame objects. The process of stacking pivots a level of column labels to the row index. Unstacking performs the opposite, pivoting a level of the row index into the column index.

One of the differences between stacking/unstacking and performing a pivot is that unlike pivots the stack and unstack functions will be able to pivot specific levels of a hierarchical index. Also, where a pivot retains the same number of levels on an index, a stack and unstack will always increase the levels on the index of one of the axes (columns for unstack and rows for stack) and decrease the levels on the other axis.

The reasons for stacking and unstacking are along the same lines as for performing pivots. Fundamentally it comes down to how you want your data organized for analysis. The organization can change the means and ease of retrieving data and deriving results. As will be...