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

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.

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.

Hands-On Approach to Regression Discontinuity Design Python
In this machine learning project, you will learn to implement Regression Discontinuity Design Example in Python to determine the effect of age on Mortality Rate in Python.

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.

Learn to Build a Siamese Neural Network for Image Similarity
In this Deep Learning Project, you will learn how to build a siamese neural network with Keras and Tensorflow for Image Similarity.

Deep Learning Project for Text Detection in Images using Python
CV2 Text Detection Code for Images using Python -Build a CRNN deep learning model to predict the single-line text in a given image.

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

End-to-End ML Model Monitoring using Airflow and Docker
In this MLOps Project, you will learn to build an end to end pipeline to monitor any changes in the predictive power of model or degradation of data.

AWS Project to Build and Deploy LSTM Model with Sagemaker
In this AWS Sagemaker Project, you will learn to build a LSTM model on Sagemaker for sales forecasting while analyzing the impact of weather conditions on Sales.