Thursday, December 26, 2024
Google search engine
HomeLanguagesTurn Pandas Multi-Index into column

Turn Pandas Multi-Index into column

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A multi-index dataframe has multi-level, or hierarchical indexing. We can easily convert the multi-level index into the column by the reset_index() method.

DataFrame.reset_index() is used to reset the index to default and make the index a column of the dataframe.

Step 1: Creating a multi-index dataframe.

Let’s see an example by making a multi-index dataframe first.

Code:

Python3




# Creating index for multi-index dataframe
tuples = [('A', 'a'), ('A', 'b'), ('B', 'a'), ('B', 'b')]
index = pd.MultiIndex.from_tuples(tuples, names=['index_1', 'index_2'])
 
# Value corresponding to the index
data = [2, 4, 6, 8]
 
# Creating dataframe using 'data' and 'index'
df = pd.DataFrame(data = data, index = index, columns = ['value'])
print(df)


Output:

Turn Pandas Multi-Index into column

DataFrame created with multi-index

Step 2: Converting index into the column.

Here we can see the hierarchical indexing, we are converting each index into a separate column using the reset_index() method.

Python3




new_df = df.reset_index()
print(new_df)


Output:

Turn Pandas Multi-Index into column

DataFrame after using reset_index() method

Here we can see that the all the levels of index are converted to columns.

We can also select which level of multi-index to reset using parameter level.

level parameter can be an index name or can be a tuple or list of indices to remove from the dataframe and make them as dataframe columns.

Code:

Python3




new_df_2 = df.reset_index(level=("index_2",))
new_df_2.head()


Output:

Turn Pandas Multi-Index into column

DataFrame after using reset_index with level parameter set.

Note: Here, we can see that only “index_2” is reset from index and has become a column, but not “index_1“.

RELATED ARTICLES

Most Popular

Recent Comments