How to apply arithmatic operations on a Pandas DataFrame?

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


Recipe Objective

Have you ever tried to apply some operation in dataframe on string and numeric data.

So this is the recipe on how we can apply arithmatic operations on a Pandas DataFrame.

Step 1 - Import the library

import pandas as pd import numpy as np

We have only imported pandas and numpy which is needed.

Step 2 - Creating DataFrame

We have created a dictionary and passed it through pd.DataFrame to create a Dataframe raw_data = {"first_name": ["Sheldon", "Raj", "Leonard", "Howard", "Amy"], "age": [42, 38, 36, 41, 35], "Comedy_Score": [9, 7, 8, 8, 5], "Rating_Score": [25, 25, 49, 62, 70]} df = pd.DataFrame(raw_data, columns = ["first_name", "age", "Comedy_Score", "Rating_Score"]) print(df)

Step 3 - Applying Different Operation

We are making each letter of string in first name as capital. For this we creating a lambda function and by which are making every letter capital. capitalizer = lambda x: x.upper() print(df["first_name"].apply(capitalizer)) Now lets say we want to find the square root of the values in the dataframe. For this we have to remove the features which has strings so we have droped the feature first name. Now using applymap we have calculated square root of each values. df = df.drop("first_name", axis=1) print(df) print(df.applymap(np.sqrt)) Now lets say we want to multiply each value by 100. So for this we have created a function times100. In which we have used if else statements to return the same value if it is a string and multiply it by 100 if it is a numeric value. We have applied this function on every value of the dataframe. def times100(x): if type(x) is str: return x elif x: return 100 * x else: return print(df.applymap(times100)) So the output comes as

  first_name  age  Comedy_Score  Rating_Score
0    Sheldon   42             9            25
1        Raj   38             7            25
2    Leonard   36             8            49
3     Howard   41             8            62
4        Amy   35             5            70

1        RAJ
3     HOWARD
4        AMY
Name: first_name, dtype: object

1        RAJ
3     HOWARD
4        AMY
Name: first_name, dtype: object

   age  Comedy_Score  Rating_Score
0   42             9            25
1   38             7            25
2   36             8            49
3   41             8            62
4   35             5            70

        age  Comedy_Score  Rating_Score
0  6.480741      3.000000      5.000000
1  6.164414      2.645751      5.000000
2  6.000000      2.828427      7.000000
3  6.403124      2.828427      7.874008
4  5.916080      2.236068      8.366600

    age  Comedy_Score  Rating_Score
0  4200           900          2500
1  3800           700          2500
2  3600           800          4900
3  4100           800          6200
4  3500           500          7000

Relevant Projects

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.

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.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Learn to prepare data for your next machine learning project
Text data requires special preparation before you can start using it for any machine learning project.In this ML project, you will learn about applying Machine Learning models to create classifiers and learn how to make sense of textual data.

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.

Data Science Project in Python on BigMart Sales Prediction
The goal of this data science project is to build a predictive model and find out the sales of each product at a given Big Mart store.

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

Mercari Price Suggestion Challenge Data Science Project
Data Science Project in Python- Build a machine learning algorithm that automatically suggests the right product prices.

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.

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.