
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - How to reset index after Groupby pandas?
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
- Related Articles
- How to reset index in Pandas dataframe?
- How to reset hierarchical index in Pandas?
- How to do groupby on a multiindex in Pandas?
- How to Groupby values count on the Pandas DataFrame
- How to change index values of a Pandas series after creation?
- Python - Sum negative and positive values using GroupBy in Pandas
- How to display Pandas Dataframe in Python without Index?
- Python Pandas - Alter index name
- Pandas GroupBy – Count the occurrences of each combination
- How to get column index from column name in Python Pandas?
- Python Pandas - Indicate duplicate index values
- How to clear the form after submitting in Javascript without using reset?
- Python - Make new Pandas Index with deleting multiple index elements
- How to select subset of data with Index Labels in Python Pandas?
- Python Pandas - Check if the Pandas Index holds Interval objects

Advertisements