17
How to Rename Multi index columns in Pandas Dataframe
Pandas dataframe is a powerful two dimensional data structure which allows you to store data in rows and columns format.
It also supports multi index for columns and rows.
In this tutorials, you'll learn how to create multi-index pandas data-frame and how to rename the columns of the multi index data-frame.
If you would like to rename columns of a single index dataframe read, How to Rename columns of Pandas Dataframe?
To create a multi index dataframe, you need to follow two steps.
First, create a normal dataframe using pd.DataFrame()
method.
Second, set the columns for the dataframe using pd.MultiIndex.from_tuples()
. This allows you to set mutli index for the columns of the dataframe.
Snippet
import pandas as pd
df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("a", "d")))
df
You'll see the below output.
Output
a
b c d
0 1 2 3
1 4 5 6
2 7 8 9
The multilevel column index dataframe is created. a is the first level column index and b, c, d are the second level column indexes.
Next, let's see how to rename these mutli-level columns.
To rename the multi index columns of the pandas dataframe, you need to use the set_levels() method.
Use the below snippet to rename the multi level columns.
Snippet
df.columns.set_levels(['b1','c1','d1'],level=1,inplace=True)
df
where,
-
['b1','c1','d1']
- New column names of the index -
level=1
- Level of the columns to be renamed -
inplace=True
- To perform the rename operation in the same dataframe rather than creating the new dataframe
Now the second level index of the columns will be renamed to b1, c1, d1 as shown below.
Output
a
b1 c1 d1
0 1 2 3
1 4 5 6
2 7 8 9
This is how you can rename the columns of the multi index dataframe.
In this short tutorial, you've learnt how to rename the columns of the multi-index pandas data-frame using the set_levels()
method.
17