Table of Contents
In Pandas, you can convert an index to a column using the .reset_index() method. This method will convert the index to the first column of the DataFrame and move the existing columns to the right. You can then specify the list of columns you would like to include in the DataFrame. This method is useful for creating a DataFrame from a series of data, as it allows you to easily add new columns and rearrange the order of the columns. It also allows you to rename the column labels, and even index them.
You can use the following basic syntax to convert an index of a pandas DataFrame to a column:
#convert index to column df.reset_index(inplace=True)
If you have a MultiIndex pandas DataFrame, you can use the following syntax to convert a specific level of the index to a column:
#convert specific level of MultiIndex to column df.reset_index(inplace=True, level = ['Level1'])
The following examples show how to use this syntax in practice.
Example 1: Convert Index to Column
The following code shows how to convert an index of a pandas DataFrame to a column:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19], 'assists': [5, 7, 7, 9, 12], 'rebounds': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 #convert index to column df.reset_index(inplace=True) #view updated DataFrame df index points assists rebounds 0 0 25 5 11 1 1 12 7 8 2 2 15 7 10 3 3 14 9 6 4 4 19 12 6
Example 2: Convert MultiIndex to Columns
Suppose we have the following MultiIndex pandas DataFrame:
import pandas as pd #create DataFrame index_names = pd.MultiIndex.from_tuples([('Level1','Lev1', 'L1'), ('Level2','Lev2', 'L2'), ('Level3','Lev3', 'L3'), ('Level4','Lev4', 'L4')], names=['Full','Partial', 'ID']) data = {'Store': ['A','B','C','D'], 'Sales': [17, 22, 29, 35]} df = pd.DataFrame(data, columns = ['Store','Sales'], index=index_names) #view DataFrame df Store Sales Full Partial ID Level1 Lev1 L1 A 17 Level2 Lev2 L2 B 22 Level3 Lev3 L3 C 29 Level4 Lev4 L4 D 35
The following code shows how to convert every level of the MultiIndex to columns in a pandas DataFrame:
#convert all levels of index to columns df.reset_index(inplace=True) #view updated DataFrame df Full Partial ID Store Sales 0 Level1 Lev1 L1 A 17 1 Level2 Lev2 L2 B 22 2 Level3 Lev3 L3 C 29 3 Level4 Lev4 L4 D 35
We could also use the following code to only convert a specific level of the MultiIndex to a column:
#convert just 'ID' index to column in DataFrame
df.reset_index(inplace=True, level = ['ID'])
#view updated DataFrame
df
ID Store Sales
Full Partial
Level1 Lev1 L1 A 17
Level2 Lev2 L2 B 22
Level3 Lev3 L3 C 29
Level4 Lev4 L4 D 35
Notice that just the ‘ID’ level was converted to a column in the DataFrame.