Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to reset index in Pandas dataframe?
In Pandas, the index serves as row labels for a DataFrame. Sometimes you need to reset the index back to the default integer sequence (0, 1, 2...) or convert a custom index into a regular column. The reset_index() method provides this functionality.
Basic reset_index() Usage
Let's start with a simple example showing how to reset a DataFrame's index ?
import pandas as pd
# Create DataFrame with default index
data = {'Name': ["Allen", "Jack", "Mark", "Vishal"],
'Marks': [85, 92, 99, 87]}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
Original DataFrame:
Name Marks
0 Allen 85
1 Jack 92
2 Mark 99
3 Vishal 87
Resetting Custom Index
When you have a custom index and want to convert it back to default integers ?
import pandas as pd
# Create DataFrame with custom index
data = {'Name': ["Allen", "Jack", "Mark", "Vishal"],
'Marks': [85, 92, 99, 87]}
custom_index = ['a', 'j', 'm', 'v']
df = pd.DataFrame(data, index=custom_index)
print("DataFrame with custom index:")
print(df)
print("\nAfter reset_index():")
df_reset = df.reset_index()
print(df_reset)
DataFrame with custom index:
Name Marks
a Allen 85
j Jack 92
m Mark 99
v Vishal 87
After reset_index():
index Name Marks
0 a Allen 85
1 j Jack 92
2 m Mark 99
3 v Vishal 87
Using inplace Parameter
Use inplace=True to modify the original DataFrame instead of creating a new one ?
import pandas as pd
data = {'Name': ["Allen", "Jack", "Mark"], 'Marks': [85, 92, 99]}
df = pd.DataFrame(data, index=['x', 'y', 'z'])
print("Before inplace reset:")
print(df)
df.reset_index(inplace=True)
print("\nAfter inplace reset:")
print(df)
Before inplace reset: Name Marks x Allen 85 y Jack 92 z Mark 99 After inplace reset: index Name Marks 0 x Allen 85 1 y Jack 92 2 z Mark 99
Dropping the Old Index
Use drop=True to discard the old index instead of adding it as a column ?
import pandas as pd
data = {'Name': ["Allen", "Jack", "Mark"], 'Marks': [85, 92, 99]}
df = pd.DataFrame(data, index=['x', 'y', 'z'])
print("Original DataFrame:")
print(df)
df_reset = df.reset_index(drop=True)
print("\nAfter reset_index(drop=True):")
print(df_reset)
Original DataFrame:
Name Marks
x Allen 85
y Jack 92
z Mark 99
After reset_index(drop=True):
Name Marks
0 Allen 85
1 Jack 92
2 Mark 99
Key Parameters
| Parameter | Default | Description |
|---|---|---|
drop |
False | If True, discards the old index |
inplace |
False | If True, modifies the original DataFrame |
level |
None | Specifies which level to reset in MultiIndex |
Conclusion
Use reset_index() to convert custom indices back to default integers. Set drop=True to discard the old index, or inplace=True to modify the original DataFrame directly.
