Python - How to reset index after Groupby pandas?

PythonServer Side ProgrammingProgramming

To reset index after group by, at first group according to a column using groupby(). After that, use reset_index().

At first, import the required library −

import pandas as pd

Create a DataFrame with 2 columns −

dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"],

      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)

Group according to Car column −

resDF = dataFrame.groupby("Car").mean()

Now, reset index after grouping −

resDF.reset_index()

Example

Following is the code −

import pandas as pd

# creating a dataframe with two columns
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Audi", "Mercedes", "Audi", "Lexus", "Mercedes", "Lexus", "Mercedes"],

      "Reg_Price": [1000, 1400, 1100, 900, 1700, 1800, 1300, 1150, 1350]
   }
)

print"DataFrame...\n",dataFrame

# grouped according to Car
resDF = dataFrame.groupby("Car").mean()

print"\nDataFrame...\n", resDF

# resetting index after grouping
print"\nReset index after grouping...\n", resDF.reset_index()

Output

This will produce the following output −

DataFrame...
        Car   Reg_Price
0      Audi       1000
1     Lexus       1400
2      Audi       1100
3  Mercedes        900
4      Audi       1700
5     Lexus       1800
6  Mercedes       1300
7     Lexus       1150
8  Mercedes       1350

DataFrame...
            Reg_Price
Car
Audi       1266.666667
Lexus      1450.000000
Mercedes   1183.333333

Reset index after grouping...
        Car   Reg_Price
0      Audi  1266.666667
1     Lexus  1450.000000
2  Mercedes  1183.333333
raja
Published on 15-Sep-2021 09:31:26
Advertisements