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.