Skip to content
Home » pandas Part 13 – Stacking and Unstacking MultiIndices

pandas Part 13 – Stacking and Unstacking MultiIndices

Spread the love

STACKING AND UNSTACKING MULTIINDICES

In this article we’ll be working on our example from the previous part. Our subject today is stacking and unstacking multi-indices. So, without further ado, let’s import pandas and numpy and let’s recreate our previous example:

In [1]:
import numpy as np
import pandas as pd

# the tuples used as indices
index = [('Company A', 2018), ('Company A', 2019),
        ('Company B', 2018), ('Company B', 2019),
        ('Company C', 2018), ('Company C', 2019)]

# the list of sales
sales = [125, 211,
        390, 455,
        475, 655]

# Let's create a Series object.
s = pd.Series(sales, index=index)

# Here's the multi-index.
m_index = pd.MultiIndex.from_tuples(index)

# Let's reindex the Series object.
s = s.reindex(m_index)

s
Out[1]:
Company A  2018    125
           2019    211
Company B  2018    390
           2019    455
Company C  2018    475
           2019    655
dtype: int64

As you prpbably noticed, the multi-indexed Series looks very much like a DataFrame. Actually, it can be easily converted to a DataFrame by means of the unstack method. There’s also the stack method, which does the contrary, so converts a DataFrame to a multi-indexed Series. Have a look:

In [2]:
# convert to DataFrame
s_df = s.unstack()
s_df
Out[2]:
2018 2019
Company A 125 211
Company B 390 455
Company C 475 655
In [3]:
# convert back to multi-indexed Series
s = s_df.stack()
s
Out[3]:
Company A  2018    125
           2019    211
Company B  2018    390
           2019    455
Company C  2018    475
           2019    655
dtype: int64

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply