How to apply arithmatic operations on a Pandas DataFrame?
DATA MUNGING

How to apply arithmatic operations on a Pandas DataFrame?

How to apply arithmatic operations on a Pandas DataFrame?

This recipe helps you apply arithmatic operations on a Pandas DataFrame

0
In [2]:
## How to apply arithmatic operations on a Pandas DataFrame
def Kickstarter_Example_72():
    print()
    print(format('How to apply arithmatic operations on a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    import numpy as np

    # Create a dataframe
    data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
            'year': [2012, 2012, 2013, 2014, 2014],
            'reports': [4, 24, 31, 2, 3],
            'coverage': [25, 94, 57, 62, 70]}
    df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
    print(); print(df)

    # Create a capitalization lambda function
    capitalizer = lambda x: x.upper()

    # Apply the capitalizer function over the column ‘name’
    # apply() can apply a function along any axis of the dataframe
    print(); print(df['name'].apply(capitalizer))

    # Map the capitalizer lambda function over each element in the series ‘name’
    # map() applies an operation over each element of a series
    print(); print(df['name'].map(capitalizer))

    # Apply a square root function to every single cell in the whole data frame
    # applymap() applies a function to every single element in the entire dataframe.
    # Drop the string variable so that applymap() can run
    df = df.drop('name', axis=1)
    print(); print(df)

    # Return the square root of every cell in the dataframe using applymap()
    print(); print(df.applymap(np.sqrt))

    # Applying A Function Over A Dataframe
    # Create a function that multiplies all non-strings by 100
    def times100(x):
        if type(x) is str: return x
        elif x:            return 100 * x
        else:              return

    # Apply the times100 over every cell in the dataframe
    print(); print(df.applymap(times100))

Kickstarter_Example_72()
*************How to apply arithmatic operations on a Pandas DataFrame*************

             name  year  reports  coverage
Cochice     Jason  2012        4        25
Pima        Molly  2012       24        94
Santa Cruz   Tina  2013       31        57
Maricopa     Jake  2014        2        62
Yuma          Amy  2014        3        70

Cochice       JASON
Pima          MOLLY
Santa Cruz     TINA
Maricopa       JAKE
Yuma            AMY
Name: name, dtype: object

Cochice       JASON
Pima          MOLLY
Santa Cruz     TINA
Maricopa       JAKE
Yuma            AMY
Name: name, dtype: object

            year  reports  coverage
Cochice     2012        4        25
Pima        2012       24        94
Santa Cruz  2013       31        57
Maricopa    2014        2        62
Yuma        2014        3        70

                 year   reports  coverage
Cochice     44.855323  2.000000  5.000000
Pima        44.855323  4.898979  9.695360
Santa Cruz  44.866469  5.567764  7.549834
Maricopa    44.877611  1.414214  7.874008
Yuma        44.877611  1.732051  8.366600

              year  reports  coverage
Cochice     201200      400      2500
Pima        201200     2400      9400
Santa Cruz  201300     3100      5700
Maricopa    201400      200      6200
Yuma        201400      300      7000

Relevant Projects

Deep Learning with Keras in R to Predict Customer Churn
In this deep learning project, we will predict customer churn using Artificial Neural Networks and learn how to model an ANN in R with the keras deep learning package.

Choosing the right Time Series Forecasting Methods
There are different time series forecasting methods to forecast stock price, demand etc. In this machine learning project, you will learn to determine which forecasting method to be used when and how to apply with time series forecasting example.

German Credit Dataset Analysis to Classify Loan Applications
In this data science project, you will work with German credit dataset using classification techniques like Decision Tree, Neural Networks etc to classify loan applications using R.

Data Science Project-All State Insurance Claims Severity Prediction
Data science project in R to develop automated methods for predicting the cost and severity of insurance claims.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

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.

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.

Zillow’s Home Value Prediction (Zestimate)
Data Science Project in R -Build a machine learning algorithm to predict the future sale prices of homes.

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.

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.