set_index() and reset_index() methods in Pandas

In Pandas, the set_index() and reset_index() methods are used to manipulate the index of a DataFrame.

• set_index() Method The set_index method assigns one or more columns to be the index of the DataFrame.

Syntax DataFrame.set_index(keys, drop=True, inplace=False)

The function has the following parameters:

Example:

Python

import pandas as pd

df = pd.DataFrame({
    'ID': [101, 102, 103],
    'Name': ['Ashish', 'Bobby', 'Senorita'],
    'Score': [90, 85, 88]
})

df_indexed = df.set_index('ID')
print(df_indexed)

The output of the above code is shown below:

set_index() method in Pandas

• reset_index() Method The reset_index() method moves the index back into a column and reset the default integer index.

Syntax DataFrame.reset_index(drop=False, inplace=False)

The function has the following parameters:

Example:

Python

df_reset = df_indexed.reset_index()
print(df_reset)

The output of the above code is shown below:

reset_index() method in Pandas

Summary Table

MethodPurposeDefault Behavior
set_index()Set column(s) as the indexRemoves the column from data
reset_index()Moves index back as a columnAdds index as a new column