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

0    SHELDON
1        RAJ
2    LEONARD
3     HOWARD
4        AMY
Name: first_name, dtype: object

0    SHELDON
1        RAJ
2    LEONARD
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
​

Download Materials

What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

Deep Learning Project for Time Series Forecasting in Python
Deep Learning for Time Series Forecasting in Python -A Hands-On Approach to Build Deep Learning Models (MLP, CNN, LSTM, and a Hybrid Model CNN-LSTM) on Time Series Data.

Hands-On Approach to Causal Inference in Machine Learning
In this Machine Learning Project, you will learn to implement various causal inference techniques in Python to determine, how effective the sprinkler is in making the grass wet.

MLOps Project for a Mask R-CNN on GCP using uWSGI Flask
MLOps on GCP - Solved end-to-end MLOps Project to deploy a Mask RCNN Model for Image Segmentation as a Web Application using uWSGI Flask, Docker, and TensorFlow.

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Build a Speech-Text Transcriptor with Nvidia Quartznet Model
In this Deep Learning Project, you will leverage transfer learning from Nvidia QuartzNet pre-trained models to develop a speech-to-text transcriptor.

Mastering A/B Testing: A Practical Guide for Production
In this A/B Testing for Machine Learning Project, you will gain hands-on experience in conducting A/B tests, analyzing statistical significance, and understanding the challenges of building a solution for A/B testing in a production environment.

Hands-On Approach to Master PyTorch Tensors with Examples
In this deep learning project, you will learn how to perform various operations on the building block of PyTorch : Tensors.

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.

Topic modelling using Kmeans clustering to group customer reviews
In this Kmeans clustering machine learning project, you will perform topic modelling in order to group customer reviews based on recurring patterns.