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]:
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]:
In [3]:
# convert back to multi-indexed Series
s = s_df.stack()
s
Out[3]:
Here’s the video version of the article: