Tutorial [Basic]: Vectorization and Pandas Iterrows, Apply, and Performance Comparison

In this tutorial, we will explore the concept of vectorization and compare it with two common alternatives, iterrows() and apply(), in the context of working with data in Pandas. We will also assess the performance differences between these methods to understand when to use each one.

Table of Contents

  1. Introduction
  2. Vectorization
  3. Using iterrows()
  4. Using apply()
  5. Performance Comparison
  6. Conclusion

1. Introduction

Pandas is a powerful library for data manipulation in Python. It provides various ways to work with data, and choosing the right method can significantly impact the performance of your code. In this tutorial, we’ll focus on vectorization and compare it with two other common techniques: iterrows() and apply().

What is Vectorization?

Vectorization is a technique in Pandas that leverages the underlying NumPy library to perform operations on entire arrays or Series, rather than iterating through individual elements. It is generally the most efficient way to work with data in Pandas.

2. Vectorization

Vectorized operations in Pandas can be applied to entire columns or Series, which results in faster and more concise code. For example, to add two columns element-wise, you can do:

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Vectorized addition
df['C'] = df['A'] + df['B']

This code adds the ‘A’ and ‘B’ columns element-wise and stores the result in a new column ‘C’. No explicit iteration is required, which makes the code more efficient.

3. Using iterrows()

The iterrows() method allows you to iterate over rows in a DataFrame, and you can apply custom functions to each row. However, it is not as efficient as vectorized operations for large datasets.

# Using iterrows() to add columns element-wise
for index, row in df.iterrows():
    df.at[index, 'C'] = row['A'] + row['B']

While iterrows() can be convenient for specific cases, it is less efficient than vectorization because it requires iteration over rows.

4. Using apply()

The apply() method allows you to apply a function to each element of a Series or DataFrame. It can be more efficient than iterrows(), but it may still be slower than vectorization.

# Using apply() to add columns element-wise
df['C'] = df.apply(lambda row: row['A'] + row['B'], axis=1)

The apply() method can be more readable than iterrows(), but for simple element-wise operations, vectorization is usually faster.

5. Performance Comparison

To compare the performance of these three methods, we can use the timeit library to measure the execution time for each approach. Let’s see an example:

import pandas as pd
import numpy as np
import timeit
 
# Create a large DataFrame
df = pd.DataFrame({'A': np.random.randint(1, 100, 10000),
                   'B': np.random.randint(1, 100, 10000)})
 
# Vectorized addition
def vectorized_addition():
    df['C'] = df['A'] + df['B']
 
# Using iterrows()
def iterrows_addition():
    for index, row in df.iterrows():
        df.at[index, 'C'] = row['A'] + row['B']
 
# Using apply()
def apply_addition():
    df['C'] = df.apply(lambda row: row['A'] + row['B'], axis=1)
 
# Measure execution time (number = 1 means: run 1 time)
vectorized_time = timeit.timeit(vectorized_addition, number=1)
iterrows_time = timeit.timeit(iterrows_addition, number=1)
apply_time = timeit.timeit(apply_addition, number=1)
 
print(f"Vectorized Time: {vectorized_time}")
print(f"iterrows Time: {iterrows_time}")
print(f"apply Time: {apply_time}")

This code compares the execution times of vectorization, iterrows(), and apply() for adding two columns in a large DataFrame. If you run those code on Google Colab, you should get similar output with me.

Vectorized Time: 0.001311236000219651
Iterrows Time: 0.7449517189998005
Apply Time: 0.1326701759999196

Based on the result, the performance order is Iterrows (0.74s – slowest), Apply (0.13s which improves 7x), then Vectorization (0.001s which improve 740x vs. Iterrows, and 100x vs. Apply).

6. Conclusion

In conclusion, vectorization is the most efficient way to perform operations on Pandas DataFrames. It is faster and more concise compared to iterrows() and apply(). However, there may be cases where iterrows() or apply() are more appropriate, especially when dealing with complex operations that cannot be easily vectorized. Always consider the trade-off between performance and code readability when choosing a method to work with your data in Pandas.

In the next tutorial, I will show the detail comparison on the common case: Feature Engineering on Date data.

[Translate] Quy định của Bộ Nội Vụ Pháp về giấy chứng nhận du lịch quốc tế (Certificate of international travel)

Mary's Journey

Cập nhật ngày 23/7/2021

Xin chào các bạn,

Để chuẩn bị cho một hành trình bay đến Ireland an toàn và suôn sẻ, mình mạn phép dịch thông tin từ trang web của Bộ Nội Vụ Pháp quy định về xuất nhập cảnh, cho các bạn nào chọn bay đường bay quá cảnh sang Pháp nhé 😊

Xem bài viết gốc 1 508 từ nữa

Vài tips chuẩn bị cho các bạn DHS Công Giáo trước khi đi du học

Mary's Journey

Xin chào các bạn,

Đối với các bạn DHS Công Giáo khi đi du học, mối quan tâm của các bạn và gia đình không chỉ là việc học hàng ngày, mà còn về việc sẽ giữ lễ Chúa Nhật và các ngày lễ buộc như thế nào nữa. Có phải các bạn đã từng lo lắng rằng khi qua đất nước mới thì “mình sẽ đi lễ ở đâu? như thế nào? nghi thức ở nhà thờ nước ngoài có khác gì ở Việt Nam không? tham gia sinh hoạt cộng đoàn như thế nào? xưng tội?” v.v không? Chia sẻ với các bạn một chút, một trong những lý do mình chọn đi du học Ireland là bởi vì Ireland là một đất nước có tỷ lệ người theo đạo Công Giáo khá cao (Báo cáo tổng kiểm tra dân s�� năm 2016 là 78.3%…

Xem bài viết gốc 1 940 từ nữa

Chia sẻ kinh nghiệm mua vé máy bay Saigon- Dublin (lần đầu)

Mary's Journey

Commercial Jet Flying Over Clouds Stock Photo - Download Image Now - iStock

Xin chào các bạn,

Bây giờ là giữa tháng 7, thời điểm này đối với các bạn DHS Việt Nam sẽ nhập học vào tháng 9, thường sẽ là đợi kết quả hồ sơ visa và chuẩn bị lên kế hoạch mua vé máy bay, đóng gói hành lý. Mình cũng vậy, bởi vì kết quả visa của mình đã OK nên mình vừa mua vé máy bay để lên đường đây 😊. Chọn mua vé máy bay trong thời điểm dịch giã như hiện tại có khá nhiều vấn đề cần lưu tâm, nên mình xin phép chia sẻ chút kinh nghiệm cá nhân của mình khi tự mua vé máy bay, như là một trong những gợi ý giúp bạn có thể lựa chọn đường bay phù hợp nhé!


Xem bài viết gốc 1 618 từ nữa

Chia sẻ kinh nghiệm thi DA-100: Analyzing Data with Microsoft Power BI trong 2 tuần

If you are looking for English version, please click here: https://blog.henryduc.codes/tips/microsoft/exams/2021/07/09/how-I-pass-DA-100-in-2-weeks.html

Hôm nay là ngày 9 tháng 7 năm 2021 và mình vừa vượt qua kỳ thi DA-100: Analyzing Data with Microsoft Power BI với điểm số rất tốt 911/1000. Và mình muốn chia sẻ với các bạn kinh nghiệm của mình trên chặng đường học tập 2 tuần này của mình.

Read More »

Bảo hiểm dành cho DHS quốc tế (Non-EU Student) tại Ireland- Study and Protect

Mary's Journey

Xin chào các bạn, mình là một du học sinh Việt Nam tại Ireland từ tháng 9, 2021. Để góp phần giúp đỡ các bạn đang có ý định du học hoặc đang làm hồ sơ du học có thêm một nguồn tham khảo đáng tin cậy, mình sẽ bắt đầu viết các bài viết và chia sẻ kinh nghiệm của mình khi chọn trường, làm hồ sơ và cuộc sống tại Ireland. Mình là sinh viên Thạc sỹ của trường TU Dublin (Technological University Dublin- ĐH công nghệ Dublin) nên mình sẽ tập trung chia sẻ về trường mình. Mong các bạn ủng hộ nhé 😊

Bài viết đầu tiên trong chuỗi bài về kinh nghiệm du học, mình chia sẻ về Bảo hiểm Study and Protect.

Trang chủ của Study& Protect

Một trong số các giấy tờ bắt buộc đối với sinh viên quốc tế theo học…

Xem bài viết gốc 768 từ nữa

Edubond- Transfermate

Mary's Journey

Xin chào các bạn, mình quay trở lại rồi đây 😊.

Ở bài viết thứ hai này, mình sẽ chia sẻ kinh nghiệm về Education Bond Ireland (tạm dịch là Trái phiếu giáo dục), gọi tắt là Edubond (nền tảng là TransferMate). Cá nhân mình ban đầu có dự định mua Edubond, nhưng sau đó vì chưa rõ quy trình mà dẫn đến tốn khá nhiều thời gian, thành ra hết hạn thanh toán với TransferMate, nên cuối cùng mình hủy giao dịch, không mua nữa. Tuy nhiên, mình cũng viết bài này để các bạn có thêm một góc nhìn và tham khảo quy trình nếu có dự định mua nhé!

Trước hết, chúng ta sẽ tìm hiểu Edubond là gì? Theo trang web EducationBondIreland, đây là một sáng kiến thị thực được hỗ trợ bởi Chính phủ Ireland và Cơ quan Nhập cư Ireland, INIS. Trái…

Xem bài viết gốc 1 308 từ nữa

CÂU CHUYỆN HACKING: HACK VÀO WINDOWS SERVER 2008 THÔNG QUA ORACLE DB 11GR2

TÓM TẮT

Bài report môn FRS401 thể hiện quá trình Hacking vào hệ thống Windows Server chứa Oracle DB 11g R2 thông qua Web Admin quản lý Oracle (Enterprise Manager). Tận dụng lỗi này, Hacker viết Python script để up shell cho IIS và phát hiện XAMPP trong Server. Hacker up tiếp shell cho PHP lên XAMPP và phát hiện ra USER-PASS của Oracle. Hacker tiến hành Reverse shell thông qua PHP để điều khiển COMMAND LINE từ xa. Từ đây, Hacker vào SQLPLUS để khai thác Oracle DB. Khi gặp trường hợp USER bị thiếu privileges, Hacker đã login vào account SYSDBA để nâng quyền cho USER. Sau cùng, Hacker dump database ra và tải về máy Hacker. Kết thúc report, Hacker trả hệ thống Server tấn công về nguyên trạng (Trả quyền lại cho USER), chỉ để lại 2 con shell và 1 shell reverse.

Disclaimer: Duck không chịu trách nhiệm nếu độc giả nào xem tài liệu này mà tấn công vào các hệ thống thực tế nhé. Only for Educational purpose thôi nhen.

Read More »

UBCx BUSMKTG1x – Module 2: Market Research, Segmentation and Targeting (Note)

This is the note for my EdX Marketing Learning. You can register to learn FREE the course Introduction to Marketing over here: https://courses.edx.org/courses/course-v1:UBCx+COMM420x+3T2017/course/ .

2.1. Introduction

In this module, you will focus on strategies and techniques for getting to know your consumer, and basing marketing decisions on the insight you gain from market research. You will also learn about targeting different segments of the market, and about frameworks and tools that you can use to identify a specific group of consumers that will be likely to respond to your marketing efforts, and inform the communication and strategic approaches that you employ.

Key Takeaways:
– Strategies and techniques for getting to know your consumer
– How to base marketing decisions on the insights you gain from market research

2.3. Market Reasearch

The purpose of Market research is to understand competitors, consumers, and the environments around us. To use the tools such as SWOT, PEST, 3Cs, we have to have a good information, with detail because one of the challenges today is we’re drowning in data, and we are lacking the good insights of the information.    

Some techniques for market reasearch for understanding customers:
– Surveys
– Focus group
– In-depth interview
– Observation

CASE STUDY: Agent Provocateur – Lingerie brand in the UK makes market research in Vancouver, Canada

Challenges:
– People were a bit uncomfortable to talk about a product like lingerie.
– How to get the best information from the consumer because lingerie is the social sensitive products?
– They want to understand consumers, competitors and understand what people think about this new product.

Technique to interview:
– Younger and not Intimidating
– Approach people on the street in Vancouver
– Offered $5 Starbucks card as a gift
–> This technique knocks down the barrier and people are open, more fun to interviewer.
–> Result: Collect 500 surveys

Hypothesis of Agent Provocateur about local consumers in Vancouver:
– They expected to be very well-known in Vancouver
– They thought people would be excited with how they do marketing (displays that feature mannequins wearing the lingerie)
– They thought that they knew who would love their product (the wealthier).

Result after analyzing survey:
– Very least people in Vancouver knew the brand. When being asked about the top brand in lingerie, people answered Victoria’s Secret
– People are divided on whether their ads was too risque (Some think it was appropriate, some not)
– The wealthier (high income) and the lower income loved this product.

Questions:
– Why did the lower income want to buy this high-end luxury products? –> It is called trade-off in consumer behaviors, when they sacrified others to save money for the expensive one.

2.4. Actionable insights through Research

A. Objective of Market Research

Data – Information – Insight
– We work with Actionable Insights, which is filtered from Information and Data.
– The actionable insight is what we use to inform the decision we make around our marketing plan
– In Market Research, we can collect new data, reuse old data, do whatever with data but the important here is what we analyze and what we do with it is what’s going to be key.

Past – Present – Future
– Data is from the Past (or Present), but decision is for the Future
– Challenge here is we have to trade-off between SPEED, COST, RISK and QUALITY of the decision.
– Question to ask: With the data, is it going to lead to a better decision? OR we wait for weeks, months and consider that the decision at that time is good or not?

    

B. Types of Market Research

UBCx BUSMKTG1x – Module 1: The Changing Nature of Marketing, Competition (Note)

This is the note for my EdX Marketing Learning. You can register to learn FREE the course Introduction to Marketing over here: https://courses.edx.org/courses/course-v1:UBCx+COMM420x+3T2017/course/.

Part 1.1: Introduction

– Examples that illustrate how marketing has continued to change and evolve over time.
– How competition impacts the dynamic landscape of marketing.
– Explore some useful marketing tools and frameworks (the 3Cs, SWOT framework, and PEST analysis)

Read More »