How to reset index in a pandas dataframe?
I have a pandas dataframe where I removed some rows. As a result, the index is now something like [1,5,6,10,11]
, but I want to reset it to [0,1,2,3,4]
. How can I achieve this?
The following approach seems to work:
df = df.reset_index()
del df['index']
However, using df = df.reindex()
does not work. What is the correct way to reset the index in a pandas dataframe?
Instead of deleting the old index manually, use drop=True
to remove it in one step:
df = df.reset_index(drop=True)
This ensures that the old index is discarded and the pandas dataframe reset index operation creates a fresh sequence starting from 0.
If you need the old index for reference but want to remove it later:
df = df.reset_index()
df = df.drop(columns=['index']) # Remove old index column
This method gives more control in case you need to keep or modify the old index before dropping it.
If reset_index() is not an option, reassign a new index using range():
df.index = range(len(df))
This manually overwrites the index, effectively mimicking a pandas dataframe reset index operation.