Pandas Groupby: Count and mean combined

Given a pandas dataframe, we have to calculate groupby count and mean combined.
By Pranit Sharma Last updated : September 17, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Calculating groupby count and mean combined

To calculate groupby and mean combined, we will use df.groupby() method along with the .agg() method by passing the columns to get their size and mean. And, rename the column name to display the result with the appropriate column name.

The groupby() method is a simple but very useful concept in pandas. By using groupby(), we can create grouping of certain values and perform some operations on those values. It splits the object, applies some operations, and then combines them to create a group hence a large amount of data and computations can be performed on these groups.

Let us understand with the help of an example,

Python program to calculate groupby count and mean combined

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'X': ['one','two','two','one','one'], 
    'Y': [10,10,20,30,30]

# Creating a DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# Using groupby and aggregate
df = df.groupby('X').agg({'X':'size', 'Y':'mean'}).rename(columns={'X':'count','Y':'mean_sent'})

# Display modified DataFrame
print("Modified DataFrame:\n",df)


The output of the above program is:

Example: Pandas Groupby: Count and mean combined

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.