W3docs

Converting a Pandas GroupBy output from Series to DataFrame

Here is an example code snippet that demonstrates how to convert the output of a Pandas GroupBy operation from a Series to a DataFrame:

Here is an example code snippet that demonstrates how to convert the output of a Pandas GroupBy operation from a Series to a DataFrame:

Convert the output of a Pandas GroupBy operation from a Series to a DataFrame

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'A': ['foo', 'bar', 'baz', 'foo', 'bar', 'baz'],
                   'B': [1, 2, 3, 4, 5, 6],
                   'C': [2.0, 3.0, 4.0, 5.0, 6.0, 7.0]})

# Perform a groupby operation on column 'A'
grouped = df.groupby('A')

# Get the mean of a specific column (returns a Series)
mean_series = grouped['B'].mean()

# Convert the Series to a DataFrame
mean_df = pd.DataFrame(mean_series)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

In this example, the groupby operation is performed on column 'A', and selecting column 'B' before calling .mean() returns a Series of mean values for each group. The pd.DataFrame() function is then used to convert the Series to a DataFrame.

Note: In modern versions of pandas, calling .mean() directly on a GroupBy object returns a DataFrame. To obtain a Series from a groupby aggregation, you must select a specific column first (e.g., grouped['B'].mean()).