How to apply functions in a Group in a Pandas DataFrame?

This recipe helps you apply functions in a Group in a Pandas DataFrame

Recipe Objective

Have you tried to apply a function on any dataset. One of the easiest way is to use apply function.

So this is the recipe on how we can apply functions in a Group in a Pandas DataFrame.

Step 1 - Import the library

import pandas as pd

We have imported pandas which will be needed for the dataset.

Step 2 - Setting up the Data

We have made a dataframe by using a dictionary. We have passed a dictionary with different values to create a dataframe. data = {"EmployeeGroup": ["A","A","A","A","A","A","B","B","B","B","B","C","C","C","C","C"], "Points": [10,40,50,70,50,50,60,10,40,50,60,70,40,60,40,60]} df = pd.DataFrame(data) print(" The Original DataFrame") print(df)

Step 3 - Training and Saving the model

We have used apply function to find Rolling Mean, Average, Sum, Maximum and Minimum. For this we have used lambda function on each and every values of the feature. print(" Rolling Mean:"); print(df.groupby("EmployeeGroup")["Points"].apply(lambda x:x.rolling(center=False,window=2).mean())) print(" Average:"); print(df.groupby("EmployeeGroup")["Points"].apply(lambda x:x.mean())) print(" Sum:"); print(df.groupby("EmployeeGroup")["Points"].apply(lambda x:x.sum())) print(" Maximum:"); print(df.groupby("EmployeeGroup")["Points"].apply(lambda x:x.max())) print(" Minimum:"); print(df.groupby("EmployeeGroup")["Points"].apply(lambda x:x.min())) So the output comes as:

The Original DataFrame
   EmployeeGroup  Points
0              A      10
1              A      40
2              A      50
3              A      70
4              A      50
5              A      50
6              B      60
7              B      10
8              B      40
9              B      50
10             B      60
11             C      70
12             C      40
13             C      60
14             C      40
15             C      60

Rolling Mean:
0      NaN
1     25.0
2     45.0
3     60.0
4     60.0
5     50.0
6      NaN
7     35.0
8     25.0
9     45.0
10    55.0
11     NaN
12    55.0
13    50.0
14    50.0
15    50.0
Name: Points, dtype: float64

Average:
EmployeeGroup
A    45.0
B    44.0
C    54.0
Name: Points, dtype: float64

Sum:
EmployeeGroup
A    270
B    220
C    270
Name: Points, dtype: int64

Maximum:
EmployeeGroup
A    70
B    60
C    70
Name: Points, dtype: int64

Minimum:
EmployeeGroup
A    10
B    10
C    40
Name: Points, dtype: int64

Download Materials

What Users are saying..

profile image

Savvy Sahai

Data Science Intern, Capgemini
linkedin profile url

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More

Relevant Projects

Langchain Project for Customer Support App in Python
In this LLM Project, you will learn how to enhance customer support interactions through Large Language Models (LLMs), enabling intelligent, context-aware responses. This Langchain project aims to seamlessly integrate LLM technology with databases, PDF knowledge bases, and audio processing agents to create a comprehensive customer support application.

Medical Image Segmentation Deep Learning Project
In this deep learning project, you will learn to implement Unet++ models for medical image segmentation to detect and classify colorectal polyps.

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

OpenCV Project to Master Advanced Computer Vision Concepts
In this OpenCV project, you will learn to implement advanced computer vision concepts and algorithms in OpenCV library using Python.

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

CycleGAN Implementation for Image-To-Image Translation
In this GAN Deep Learning Project, you will learn how to build an image to image translation model in PyTorch with Cycle GAN.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

Learn How to Build a Logistic Regression Model in PyTorch
In this Machine Learning Project, you will learn how to build a simple logistic regression model in PyTorch for customer churn prediction.

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this data science project, you will learn how to perform market basket analysis with the application of Apriori and FP growth algorithms based on the concept of association rule learning.

Classification Projects on Machine Learning for Beginners - 2
Learn to implement various ensemble techniques to predict license status for a given business.