Promote an identifier column to the index
Use a meaningful identifier column as row labels for selection and alignment.
Pandas · Module
Sets DataFrame row labels from one or more existing columns or same-length arrays. It can replace the current index or add levels to it.
Call this method with one column or array to create a regular index, or with multiple keys to create a MultiIndex. By default, selected columns are removed from the returned DataFrame; use append to retain the existing index and inplace to modify the object instead of returning a new DataFrame.
DataFrame.set_index(*keys, ***, drop=True, append=False, inplace=False, verify_integrity=False)| Name | Type | Description |
|---|---|---|
keys | label or array-like or list of labels/arrays | Column label, array-like value, or list combining labels and arrays. Arrays must match the DataFrame length. |
drop | bool, default True | Remove the columns used to form the new index. |
append | bool, default False | Add the new levels to the existing index. |
inplace | bool, default False | Modify the DataFrame instead of creating a new one. |
verify_integrity | bool, default False | Check the new index for duplicate labels. |
DataFrame or None: changed row labels, or None when inplace=True.
import pandas as pd
df = pd.DataFrame({
"year": [2024, 2024, 2025],
"month": [1, 2, 1],
"sales": [10, 20, 30],
})
result = df.set_index(["year", "month"])
print(result)Creates a MultiIndex from the year and month columns while leaving the original DataFrame unchanged.
Use a meaningful identifier column as row labels for selection and alignment.
Combine several columns into hierarchical row labels.
Add grouping dimensions to an already indexed DataFrame.
The method builds row labels from one or more existing column names or same-length array-like values. One key produces an Index, while multiple keys can produce a MultiIndex.
Follow-up: How can an external sequence participate? Pass it in the keys list; it must have the same length as the DataFrame.
drop defaults to True, so columns used as index levels are removed from the resulting DataFrame. Set drop=False to retain them as ordinary columns.
Follow-up: What changes when append=True? The supplied keys are added to the current index rather than replacing it.
By default, the method returns a DataFrame with changed row labels and does not mutate the caller. With inplace=True, it changes the DataFrame and returns None.
Follow-up: How can duplicate labels be checked during the operation? Set verify_integrity=True, accepting the additional validation cost.
DataFrame.reset_indexDataFrame.reindex