set_index() and reset_index() (Pandas)

set_index() promotes one or more columns to become the DataFrame's row index, while reset_index() does the reverse, turning the index back into ordinary columns and restoring a default integer index.

Pandas

set_index('id') makes a column the label for each row, which speeds up loc lookups and enables index-based alignment and joins. Pass a list of columns to build a MultiIndex. The chosen columns leave the body of the frame and become the index.

reset_index() is the cleanup step after grouping or pivoting: it flattens a custom or hierarchical index back into columns so the frame is flat and easy to export. Use drop=True when you want to discard the old index entirely rather than keep it as a column.

Together they let you move data freely between 'index' and 'column' roles, which is central to reshaping and to controlling how operations align.

Syntax

df.set_index(keys, drop=True)  |  df.reset_index(drop=False)

Examples

Python

import pandas as pd
df = pd.DataFrame({"k": ["a", "b"], "v": [1, 2]})
print(df.set_index("k"))

Output:

   v
k   
a  1
b  2

Learn it in a lesson

See also

Back to the Dictionary