Search code examples
pythonindexingpandasdataframe

How to reset index in a pandas dataframe?


I have a dataframe from which I remove some rows. As a result, I get a dataframe in which index is something like [1,5,6,10,11] and I would like to reset it to [0,1,2,3,4]. How can I do it?


The following seems to work:

df = df.reset_index()
del df['index']

The following does not work:

df = df.reindex()

Solution

  • DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

    df = df.reset_index(drop=True)
    

    If you don't want to reassign:

    df.reset_index(drop=True, inplace=True)