Knowledge base / Python
pandas set_index: labels, columns and reset_index
I explain index changes, drop, append and MultiIndex using separate frames, with duplicate checks and a return to ordinary columns.

I have an order number in a column and want to select records by that number. DataFrame.set_index gives the rows suitable labels. I also need to track whether the column remains in the data, how duplicates behave and which version of the frame the next example uses.
This entry covers one method and the necessary return through reset_index. It follows the pandas 3.1.1 documentation. Each alternative has its own variable, so a later example does not accidentally assume that a column removed earlier still exists.
An index is a label rather than a position
I use three synthetic orders, deliberately written in the order 102, 101, 103:
import pandas as pd
base = pd.DataFrame({
"order_id": [102, 101, 103],
"region": ["North", "South", "North"],
"units": [3, 2, 5],
})
indexed = base.set_index("order_id")
set_index uses existing columns or suitable arrays as row labels. Here, indexed has index values 102, 101 and 103, named order_id. Its remaining columns are region and units. The base frame still has all three columns and its initial positional index.
| order_id index | region | units |
|---|---|---|
| 102 | North | 3 |
| 101 | South | 2 |
| 103 | North | 5 |
Changing the index does not sort the rows. If I need label order, I consider a separate sort_index operation. The numerical value of a label does not tell me the record’s position in the frame.
loc and iloc answer different questions
For indexed, indexed.loc[101, "units"] selects label 101 and gives 2. The expression indexed.iloc[0]["units"] selects the first row positionally and gives 3. For this simple case I prefer the single access indexed.iloc[0, 1], where the second column is units.
The pandas indexing guide explains label and positional selection. A number supplied to loc remains a label even if the index is numeric. I do not interchange loc and iloc merely because both expressions happen to contain numbers.
A missing label in an ordinary loc selection raises KeyError. That differs from an existing row whose units value is missing. I first check that the selected label and identifier type are correct instead of immediately filling an apparent absence with zero.
Keep the column with drop=False
The default drop=True removes the column used for indexing from the result’s columns. If I also need it as an ordinary field, I create another variant:
kept = base.set_index("order_id", drop=False)
In kept, order_id is both the index name and a column containing the values. This does not create extra orders. The arrangement of labels changes while the frame still has three rows. Later operations may need care if they find that name ambiguous or attempt to insert a column that already exists.
Every alternative in this text starts from base unless I explicitly specify indexed. I do not call indexed.set_index("order_id") assuming order_id remains a column. The first call moved it into the index. The next operation must therefore start deliberately from an object containing the required columns.
Multiple columns create a MultiIndex
If I identify an observation with region and order_id together, I can create a hierarchical index:
multi = base.set_index(["region", "order_id"])
Its labels are the pairs (North, 102), (South, 101) and (North, 103). The single remaining column, units, contains 3, 2 and 5. The order of levels follows the supplied list and matters when selecting data afterwards.
I do not claim that every table needs a MultiIndex. Ordinary columns can be clearer in a report. I choose a hierarchical index when it helps a particular operation and I can explain its levels to the next person. A more elaborate label does not by itself prove that the business key is correct.

append adds to the existing index
Starting from indexed, which has an order_id index and a region column, I can append region as another level:
expanded = indexed.set_index("region", append=True)
The pairs now appear as (102, North), (101, South) and (103, North). This level order differs from multi. The remaining column is units. Calling append=True directly on base would append to its initial index rather than automatically to order_id.
Before using append, I name the current index explicitly. The parameter describes a relationship to the current object. It cannot infer my intention to preserve order numbers if I have not made them the index. Reading the input state prevents a hierarchical result from acquiring accidental row numbering.
Duplicates need a separate decision
A pandas index can contain repeated labels. set_index does not automatically impose a database primary-key uniqueness constraint. Two product lines belonging to the same order can legitimately share order_id, but selecting one label may then return multiple records.
The index.is_unique property indicates whether labels are unique. It is True for our indexed frame. When duplicates exist, I decide whether to retain multiple observations, add another field to the key or repair the source. I do not discard records before understanding what they represent.
The pandas 3.1.1 documentation marks verify_integrity as deprecated since 3.0.0 and directs readers to inspect is_unique on the result. I therefore avoid building a new example around that parameter. The Duplicate Labels guide explains wider consequences of repeated labels.
reset_index can restore or discard labels
For indexed, I can restore order_id as an ordinary column:
restored = indexed.reset_index()
By default, reset_index moves the previous index into columns and supplies a default index. Here that restores order_id, region and units. With drop=True, order_id labels would be discarded instead, so it is a different choice from retaining the information as a column.
The kept variant differs because order_id already remains among its columns. An ordinary reset_index can then encounter a name conflict. In that case, kept.reset_index(drop=True) removes the index while retaining the existing order_id column. I always identify the starting object rather than presenting reset as a universally interchangeable step.
I avoid inplace=True in new examples. The documentation marks the parameter as deprecated since pandas 3.1.0, with removal planned for 4.0. Assigning the result to a new variable is clear here and allows comparison between alternatives. I attach no unmeasured performance promise to that stylistic choice.
Exercise: describe the frame’s state
For base, indexed, kept, multi and expanded, list the index name or levels and the remaining columns. Then predict how to retrieve units for order 101 and explain why the first row still belongs to order 102. This checks the distinction between a label and a position.
Finally consider two lines belonging to order 101. Should order_id alone be unique, or should the key include the line number? The answer comes from the data. For adding fields, return to assign, where index labels affect how Series values align.
Key takeaways
Does set_index sort rows?
No. It changes row labels; sorting by the index is a separate sort_index operation.
Why can another set_index call raise KeyError?
An earlier call with default drop=True may have removed that field from the result's columns. Check the current object or start from the source frame.
Must the index be unique?
pandas allows duplicate labels. When the task requires uniqueness, inspect index.is_unique and establish the appropriate data key.
AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.
