How to reset index after Groupby pandas?
Last Updated :
11 Dec, 2020
Python’s groupby() function is versatile. It is used to split the data into groups based on some criteria like mean, median, value_counts, etc. In order to reset the index after groupby() we will use the reset_index() function.
Below are various examples which depict how to reset index after groupby() in pandas:
Example 1
Python3
import numpy as np
import pandas as pd
df = pd.DataFrame({ 'Subject' : [ 'Physics' ,
'Chemistry' ,
'Maths' ],
'Marks' : [ 4 , 8 , 5 ]})
df_grouped = df.groupby([ 'Subject' ]).mean()
df_grouped
|
Output:
Resetting the index after grouping data, using reset_index(), it is a function provided by python to add indexes to the data.
Output:
Example 2:
Creating Dataframe.
Python3
import pandas as pd
import numpy as np
df2 = pd.DataFrame({ 'Student' : [ 1 , 2 , 3 , 4 , 1 , 3 , 2 , 4 , 1 , 2 , 4 , 3 ],
'Amount' : [
10 , 20 , 30 , 40 , 20 , 60 , 40 , 80 , 30 , 60 , 120 , 90 ]})
df2_group = df2.groupby([ 'Student' ])
df2_grouped = df2_group[ 'Amount' ].value_counts()
print (df2_grouped)
|
Output:
Resetting the index. This will give you an error.
Python3
df2_grouped.reset_index()
|
Output:
Naming the reset_index() will group and reset the index.
Python3
df2_grouped.reset_index(name = 'count' )
|
Output:
Example 3
Here, is another example to depict how to reset dataframe after using groupby().
Python3
import numpy as np
import pandas as pd
df = pd.DataFrame({ 'Subject' : [ 'B' ,
'C' ,
'A' , 'D' , 'C' , 'B' , 'A' ],
'Marks' : [ 4 , 8 , 5 , 9 , 8 , 1 , 0 ]})
df_grouped = df.groupby([ 'Subject' ]).mean()
df_grouped
df_grouped.reset_index()
|
Output:
Share your thoughts in the comments
Please Login to comment...