Categories
Python Answers

Hoe to convert a Python Pandas GroupBy output from Series to DataFrame?

Spread the love

To convert a Python Pandas GroupBy output from Series to DataFrame, we can use the reset_index method.

For instance, we write

import pandas

df1 = pandas.DataFrame( { 
    "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , 
    "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } )

g1 = df1.groupby( [ "Name", "City"] ).count().reset_index()

to call groupby to group the Name and City columns.

And then we call count to get the count of the group by values in a series.

And then we call reset_index to return the values as a daatframe.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *