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

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

Predict Macro Economic Trends using Kaggle Financial Dataset
In this machine learning project, you will uncover the predictive value in an uncertain world by using various artificial intelligence, machine learning, advanced regression and feature transformation techniques.

Data Science Project-TalkingData AdTracking Fraud Detection
Machine Learning Project in R-Detect fraudulent click traffic for mobile app ads using R data science programming language.

Predict Credit Default | Give Me Some Credit Kaggle
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.

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.

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

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.

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.

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.

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.