SETTING AND RESETTING INDICES
In the previous part of the Pandas series we were talking about sorting indices. Today we’ll be talking about another way of rearranging multi-indexed data, index setting and resetting. Let’s start with the latter. You can use the reset_index method if you want to turn index labels into columns. Let’s use the example from the previous article to demonstrate this:
In [2]:
import numpy as np
import pandas as pd
index = pd.MultiIndex.from_product([['Columbus', 'Seattle', 'Denver', 'Dallas'], [2019, 2020]])
data = pd.Series(np.random.rand(8), index=index)
data.index.names = ['city', 'year']
data
Out[2]:
And now let’s reset the index. This will produce a DataFrame with the index labels ‘city’ and ‘year’ turned into column names. We’ll also pass the name for the data column:
In [5]:
data_reset = data.reset_index(name='result')
data_reset
Out[5]:
This was resetting the index. You can also do the opposite. By setting the index you will turn a DataFrame into a multiply indexed DataFrame:
In [6]:
data_reset.set_index(['city', 'year'])
Out[6]: