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

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

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

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

0
This data science python source code does the following: 1. Creates groups of selected variable for data preprocessing. 2.Creats your own data dictionary and converts them into Pandas dataframe format. 3. Applying groupby function to selected columns.
In [1]:
## How to apply functions in a Group in a Pandas DataFrame
def Kickstarter_Example_69():
    print()
    print(format('How to apply functions in a Group in a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Create an example 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('\nThe Original DataFrame'); print(df)

    # Apply A Function (Rolling Mean) To The DataFrame, By Group
    print('\nRolling Mean:'); print(df.groupby('EmployeeGroup')['Points'].apply(lambda x:x.rolling(center=False,window=2).mean()))

    # Apply A Function (Mean) To The DataFrame, By Group    
    print('\nAverage:'); print(df.groupby('EmployeeGroup')['Points'].apply(lambda x:x.mean()))

    # Apply A Function (Sum) To The DataFrame, By Group    
    print('\nSum:'); print(df.groupby('EmployeeGroup')['Points'].apply(lambda x:x.sum()))

    # Apply A Function (Max) To The DataFrame, By Group    
    print('\nMaximum:'); print(df.groupby('EmployeeGroup')['Points'].apply(lambda x:x.max()))

    # Apply A Function (Min) To The DataFrame, By Group    
    print('\nMinimum:'); print(df.groupby('EmployeeGroup')['Points'].apply(lambda x:x.min()))

Kickstarter_Example_69()
*************How to apply functions in a Group in a Pandas DataFrame**************

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

Relevant Projects

Predict Employee Computer Access Needs in Python
Data Science Project in Python- Given his or her job role, predict employee access needs using amazon employee database.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

Perform Time series modelling using Facebook Prophet
In this project, we are going to talk about Time Series Forecasting to predict the electricity requirement for a particular house using Prophet.

Predict Census Income using Deep Learning Models
In this project, we are going to work on Deep Learning using H2O to predict Census income.

Human Activity Recognition Using Smartphones Data Set
In this deep learning project, you will build a classification system where to precisely identify human fitness activities.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

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.

Solving Multiple Classification use cases Using H2O
In this project, we are going to talk about H2O and functionality in terms of building Machine Learning models.