![]() |
VOOZH | about |
If a DataFrame has a non-continuous or unordered index, you can reset it to a default integer index starting from 0. For example, suppose the current DataFrame has this index: [0, 2, 4, 5, 7], after resetting the index, it becomes [0, 1, 2, 3, 4].
We are going to use the following DataFrame for examples in this article:
Output
Name Age City Qualification
0 Liam 28 London MBA
1 Emma 24 Paris MA
2 Noah 22 Berlin BSc
3 Olivia 32 Madrid PhD
4 Ethan 19 Rome BA
Now, let’s explore different methods to reset the index in a DataFrame.
You can assign a custom index to a DataFrame while keeping the default integer index intact. This allows you to preserve the original order while having a meaningful identifier.
Example: In this example, we set a custom index and reset it to keep the default numeric index.
Output
index Name Age City Qualification
0 a Liam 28 London MBA
1 b Emma 24 Paris MA
2 c Noah 22 Berlin BSc
3 d Olivia 32 Madrid PhD
4 e Ethan 19 Rome BA
Explanation: The custom index becomes a new column (index), while the DataFrame now has the default integer index.
You can replace the default numeric index completely by assigning a custom index during DataFrame creation.
Example: In this example, a custom index replaces the default integer index.
Output
Name Age City Qualification
a Liam 28 London MBA
b Emma 24 Paris MA
c Noah 22 Berlin BSc
d Olivia 32 Madrid PhD
e Ethan 19 Rome BA
Explanation: The DataFrame now uses the custom index (a to e) as its row identifiers instead of integers.
You can revert a custom index back to the default numeric index, optionally removing the custom index column.
Example: In this example, a DataFrame with a custom index is reset to a default integer index.
Output
Name Age City Qualification
0 Liam 28 London MBA
1 Emma 24 Paris MA
2 Noah 22 Berlin BSc
3 Olivia 32 Madrid PhD
4 Ethan 19 Rome BA
Explanation: The custom index is removed and the DataFrame now has a standard integer index starting from 0.
You can set one of the DataFrame columns as the index and remove the default integer index.
Example: In this example, the Age column is used as the DataFrame index.
Output
Name City Qualification
Age
28 Liam London MBA
24 Emma Paris MA
22 Noah Berlin BSc
32 Olivia Madrid PhD
19 Ethan Rome BA
Explanation: The Age column is now the index, replacing the default integer index.
You can assign a column as the index while retaining the default integer index. This allows dual indexing in the DataFrame.
Example: In this example, the Age column is set as an index but the default integer index is preserved.
Output
Age Name City Qualification
0 28 Liam London MBA
1 24 Emma Paris MA
2 22 Noah Berlin BSc
3 32 Olivia Madrid PhD
4 19 Ethan Rome BA
Explanation: The Age column is restored as a normal column while keeping the default integer index.