How to apply arithmatic operations on a Pandas DataFrame?
DATA MUNGING DATA CLEANING PYTHON MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

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

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.

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.

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.

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.

Music Recommendation System Project using Python and R
Machine Learning Project - Work with KKBOX's Music Recommendation System dataset to build the best music recommendation engine.

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this NLP AI application, we build the core conversational engine for a chatbot. We use the popular NLTK text classification library to achieve this.

Predict Macro Economic Trends using Kaggle Financial Dataset
In this machine learning project, you will uncover the predictive value in an uncertain world by using various artificial intelligence, machine learning, advanced regression and feature transformation techniques.

Identifying Product Bundles from Sales Data Using R Language
In this data science project in R, we are going to talk about subjective segmentation which is a clustering technique to find out product bundles in sales data.

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.

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.