Get startedGet started for free

Unstacking DataFrames

1. Unstacking DataFrames

In the previous video, we started to work with DataFrames with multi-level indexes.

2. Review

We learned how to reshape them by converting the data into a stacked form using the stack method.

3. Undoing stacking process

Now, the questions is: Can we reshape a stacked DataFrame back into an unstacked form?

4. The .unstack() method

The answer is yes. Pandas provides us with the unstack() method. The unstacking process performs exactly the inverse operation of stacking.

5. The .unstack() method

So, unstacking means rearranging the innermost row index to become the innermost column index.

6. Unstack Series

Let's look at this stacked series again. We can see that it has three row index levels.

7. Unstack Series

If we apply the unstack() method, we can see that the innermost row level has now moved to the innermost column level. If you remember, this is the original DataFrame we have before the stacking operation.

8. Unstacking a DataFrame

unstack() can also be applied to DataFrames. We'll use the stacked DataFrame we got previously.

9. Unstacking a DataFrame

We apply the unstack() method. As a result, we can see that the last row level, the feature level has moved to the column level. Again, we got the original DataFrame we have before the stacking operation.

10. Unstack a level

Of course, we can also choose which level to unstack. To that aim, we set the level argument to the index number or the index name as we did with the stack() method.

11. Unstack level by number

Let's see an example. We want to unstack the first row level of churn_stacked. We set the level argument to zero. In the output, we can see how this level has moved to the column index. Remember that if we don't set the level argument, unstack() moves the last column level by default.

12. Unstack level by name

We can do the same but using a level name. We set the level argument to credit_card. As a result, the reshaped DataFrame has the credit_card level moved to the column index. Notice that the stack() and unstack() methods implicitly sort the index levels.

13. Sort index

To change that, we can use the sort_index() method. In our example, we set the ascending argument to False. The resulting DataFrame contains the row indices sorted by descending order.

14. Rearranging levels

One useful way to rearrange levels is to chain the stacking and unstacking processes. Let's unstack the second row level and then, stack the first column level. In the output, we see that the row level named first appears now in the column index. Also, the column level named year has moved to the row index.

15. Let's practice!

Let's unstack some DataFrames.