![]() |
VOOZH | about |
If a DataFrame has a column whose values naturally identify each row (like IDs, names, or timestamps), you can make that column the row index. For example, if your DataFrame has a column Name with values ["Akash", "Geeku", "Pankaj"], after converting it to the index, these names become the row labels instead of the default 0, 1, 2.
Consider this DataFrame which we will use in all examples:
Person Dept Score 0 Zoe Sales 88 1 Max IT 92 2 Liam HR 75 3 Nora Finance 85 4 Owen IT 90
Now let’s explore methods one by one
DataFrame.set_index(col) is the standard, explicit way to make a column the index. It returns a new DataFrame (or modifies in-place with inplace=True) and can drop the column from the columns list immediately.
Example: This example uses set_index() to make "Person" the index.
Output
Dept Score
Person
Zoe Sales 88
Max IT 92
Liam HR 75
Nora Finance 85
Owen IT 90
Explanation:
df.index = df.pop(col) removes the column and assigns its values to the index in one step concise and efficient for in-place updates.
Example: This example sets the index by popping "Person" from the DataFrame.
Output
Dept Score
Person
Zoe Sales 88
Max IT 92
Liam HR 75
Nora Finance 85
Owen IT 90
Explanation:
You can assign df.index = df[col]. This sets the index but does not remove the original column you’ll often want to drop() it afterwards.
Example: This example assigns "Person" as index while keeping the column (then shows how to drop it).
Output
After assigning index (column still present):
Person Dept Score
Person
Zoe Zoe Sales 88
Max Max IT 92
Liam Liam HR 75
Nora Nora Finance 85
Owen Owen IT 90
After dropping the original column:
Dept Score
Person
Zoe Sales 88
Max IT 92
Liam HR 75
Nora Finance 85
Owen IT 90
Explanation: