Return GroupBy Object Back to New pandas DataFrame in Python (Example Code)

In this article, I’ll show how to display a GroupBy object as a regular pandas DataFrame in Python.

Setting up the Example

import pandas as pd                                 # Import pandas library
my_df = pd.DataFrame({'A':range(19, 28),            # Constructing a pandas DataFrame
                      'B':[6, 7, 3, 9, 1, 3, 8, 8, 9],
                      'C':range(20, 11, - 1),
                      'GRP_a':['gr1', 'gr1', 'gr2', 'gr3', 'gr1', 'gr2', 'gr2', 'gr3', 'gr3'],
                      'GRP_b':['x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'y']})
print(my_df)
#     A  B   C GRP_a GRP_b
# 0  19  6  20   gr1     x
# 1  20  7  19   gr1     x
# 2  21  3  18   gr2     x
# 3  22  9  17   gr3     x
# 4  23  1  16   gr1     y
# 5  24  3  15   gr2     y
# 6  25  8  14   gr2     y
# 7  26  8  13   gr3     y
# 8  27  9  12   gr3     y

Example: Create Regular pandas DataFrame from GroupBy Object

my_df_gr = my_df.groupby(['GRP_a', 'GRP_b']).sum()  # GroupBy pandas DataFrame
print(my_df_gr)
#               A   B   C
# GRP_a GRP_b            
# gr1   x      39  13  39
#       y      23   1  16
# gr2   x      21   3  18
#       y      49  11  29
# gr3   x      22   9  17
#       y      53  17  25
my_df_gr_updated = my_df_gr.reset_index()           # Convert grouped index back
print(my_df_gr_updated)
#   GRP_a GRP_b   A   B   C
# 0   gr1     x  39  13  39
# 1   gr1     y  23   1  16
# 2   gr2     x  21   3  18
# 3   gr2     y  49  11  29
# 4   gr3     x  22   9  17
# 5   gr3     y  53  17  25

Further Resources

Have a look at the following Python tutorials. They discuss topics such as lists and data conversion:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top