How to reduce usage of for loop by using apply?
MACHINE LEARNING RECIPES DATA CLEANING PYTHON DATA MUNGING PANDAS CHEATSHEET     ALL TAGS

How to reduce usage of for loop by using apply?

How to reduce usage of for loop by using apply?

This recipe helps you reduce usage of for loop by using apply

0

Recipe Objective

While working with python over dataframes, for iteration, we generally use loops. However the time required is considerably high if we start using large dataset. To optimize the present problem, an other way round for the same is using apply function

So this recipe is a short example on how to reduce usage of for loop by using apply function. We will also compare time taken by apply function and with for loop. Let's get started.

Step 1 - Import the library

import pandas as pd import seaborn as sb import time

Let's pause and look at these imports. Pandas is generally used for data manipulation and analysis. Here, seaborn is just taken to import some predefined datasets. Time library is generally used for controlling time while operating with commands.

Step 2 - Setup the Data

df = sb.load_dataset('tips') print(df.head())

We have imported data tips datasert from seaborn library in here.

Step 3 - Iterating using apply over total_bill column and calculating time taken in

start= time.time() df['total_bill']=df['total_bill'].apply(lambda x:x*2) print(time.time()-start) print(df.head())

In 1st line, we started our time like a stopwatch. Now using apply function, iterating over total_bill column. Now finally we print the time taken to iterate and the updated dataset.

Step 4 - Iterating using for loop over total_bill column and calculating time taken in

start=time.time() for i in range(0,len(df)): df['total_bill'][i]=df['total_bill'][i]*2 print(time.time()-start)

In 1st line, we started our time like a stopwatch. Now using for loop, iterating over total_bill column. Now finally we print the time taken to iterate and the updated dataset.

Step 5 - Lets look at our dataset now

Once we run the above code snippet, we will see:

Scroll down to the ipython notebook below to see the output.

A clear difference in time taken could be observed. For loop took around 0.5 secs while apply function took 0.007 secs.

Relevant Projects

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

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.

Data Science Project on Wine Quality Prediction in R
In this R data science project, we will explore wine dataset to assess red wine quality. The objective of this data science project is to explore which chemical properties will influence the quality of red wines.

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

Forecast Inventory demand using historical sales data in R
In this machine learning project, you will develop a machine learning model to accurately forecast inventory demand based on historical sales data.

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.

Natural language processing Chatbot application using NLTK for text classification
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.

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.

Solving Multiple Classification use cases Using H2O
In this project, we are going to talk about H2O and functionality in terms of building Machine Learning models.

Machine Learning or Predictive Models in IoT - Energy Prediction Use Case
In this machine learning and IoT project, we are going to test out the experimental data using various predictive models and train the models and break the energy usage.