+4 votes
in Programming Languages by (27.1k points)
I want to reset the index of a DataFrame to its default values (0, 1, 2, ...). How can I do this?

1 Answer

+2 votes
by (45.8k points)

You can use the reset_index() function to reset the DataFrame index to its default value. This function will also add 'index' as a new column. To drop it, you can use this function with 'drop=True' parameter.

Here is an example:

>>> import pandas as pd
>>> df=pd.DataFrame({'A':[1,2,3,4,5], 'B':[10,20,30,40,50]})
>>> df
   A   B
0  1  10
1  2  20
2  3  30
3  4  40
4  5  50
>>> df1=df.set_index('C')
>>> df1
    A   B
C        
11  1  10
12  2  20
13  3  30
14  4  40
15  5  50

Without 'drop' parameter

>>> df.reset_index()
   index  A   B   C
0      0  1  10  11
1      1  2  20  12
2      2  3  30  13
3      3  4  40  14
4      4  5  50  15

With 'drop' parameter

>>> df.reset_index(drop=True)
   A   B   C
0  1  10  11
1  2  20  12
2  3  30  13
3  4  40  14
4  5  50  15
 


...