• Reset index in pandas using “reset_index” method of pandas dataframe.

  • When we perform slicing or filtering operations on Pandas Dataframe, the resulting dataframe retains original indices which might cause issues in further index based operations. In the below example we first create a pandas dataframe then we filter on the basis of color. Finally we reset the index of filtered dataframe. 

# Imports 

import pandas as pd

# Let's create a dataframe
data = {'Color': ['Red', 'Red', 'Green', 'Blue', 'Red', 'Green'],
        'Shape': ['Circle', 'Square', 'Square', 'Triangle', 'Circle', 'Triangle'],
        'Value': [1, 1, 2, 1, 3, 3]}

df = pd.DataFrame(data)
df
ColorShapeValue
0RedCircle1
1RedSquare1
2GreenSquare2
3BlueTriangle1
4RedCircle3
5GreenTriangle3
# Let's filter green color entries
greens = df[df.Color == 'Green']
greens
ColorShapeValue
2GreenSquare2
5GreenTriangle3
greens.index
Int64Index([2, 5], dtype='int64')
# To reset index
greens.reset_index(drop=True, inplace=True)
# Drop will drop the original index
greens
ColorShapeValue
0GreenSquare2
1GreenTriangle3