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

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python
In this machine learning regression project, you will learn to build NumPy Regression Models (Linear Regression, Ridge Regression, Lasso Regression) from Scratch.

Build Portfolio Optimization Machine Learning Models in R
Machine Learning Project for Financial Risk Modelling and Portfolio Optimization with R- Build a machine learning model in R to develop a strategy for building a portfolio for maximized returns.

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

Langchain Project for Customer Support App in Python
In this LLM Project, you will learn how to enhance customer support interactions through Large Language Models (LLMs), enabling intelligent, context-aware responses. This Langchain project aims to seamlessly integrate LLM technology with databases, PDF knowledge bases, and audio processing agents to create a comprehensive customer support application.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Census Income Data Set Project-Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based oncensus data.

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.