All programming languages are inseparable from loops. So, by default, we start executing a loop whenever there is a repeating operation. But when we are dealing with large number of iterations (millions/billions of rows), using loops is a crime. You might be stuck for a few hours, only to realize later that it doesn't work. This is where implementing vectorization in python becomes very critical.
What is vectorization?
Vectorization is a technique for implementing (NumPy) array operations on data sets. Behind the scenes, it applies the operation to all elements of the array or series at once (unlike a "for" loop that operates one row at a time).
Next we use some use cases to demonstrate what vectorization is.
Find the sum of numbers
##使用循环 import time start = time.time() # iterative sum total = 0 # iterating through 1.5 Million numbers for item in range(0, 1500000): total = total + item print('sum is:' + str(total)) end = time.time() print(end - start) #1124999250000 #0.14 Seconds
## 使用矢量化 import numpy as np start = time.time() # vectorized sum - using numpy for vectorization # np.arange create the sequence of numbers from 0 to 1499999 print(np.sum(np.arange(1500000))) end = time.time() print(end - start) ##1124999250000 ##0.008 Seconds
The execution time of vectorization is reduced by about 18 times compared to iteration using range functions. This difference becomes even more significant when using Pandas DataFrame.
Math Operations
In data science, when working with Pandas DataFrame, developers use loops to create new derived columns through mathematical operations.
In the example below we can see how easy it is to replace loops with vectorization for such use cases.
DataFrame is tabular data in the form of rows and columns.
We create a pandas DataFrame with 5 million rows and 4 columns filled with random values between 0 and 50.
import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint( 0 , 50 , size=( 5000000 , 4 )), columns=( 'a' , 'b' , 'c' , 'd ' )) df.shape # (5000000, 5) df.head()
Create a new column "ratio" to find the ratio of columns "d" and "c".
## 循环遍历 import time start = time.time() # 使用 iterrows 遍历 DataFrame for idx, row in df.iterrows(): # 创建一个新列 df.at[idx, 'ratio' ] = 100 * (row[ "d" ] / row[ "c" ]) end = time.time() print (end - start) ### 109 秒
## 使用矢量化 start = time.time() df[ "ratio" ] = 100 * (df[ "d" ] / df[ "c" ]) end = time.time() print (end - start) ### 0.12 秒
We can see significant improvements with the DataFrame, with the vectorized operation taking almost 1000 times faster compared to the loop in Python.
If-else statement
We have implemented many operations that require us to use "If-else" type logic. We can easily replace this logic with vectorized operations in python.
Let's see the following example to understand it better (we will use the DataFrame we created in use case 2):
Imagine that we want to create a data based on the existing column "a" Create a new column "e" with some condition on
## 使用循环 import time start = time.time() # 使用 iterrows 遍历 DataFrame for idx, row in df.iterrows(): if row.a == 0 : df.at[idx, 'e' ] = row.d elif ( row.a <= 25 ) & (row.a > 0 ): df.at[idx, 'e' ] = (row.b)-(row.c) else : df.at[idx, 'e' ] = row.b + row.c end = time.time() print (end - start) ### 耗时:166 秒
## 矢量化 start = time.time() df[ 'e' ] = df[ 'b' ] + df[ 'c' ] df.loc[df[ 'a' ] <= 25 , 'e' ] = df [ 'b' ] -df[ 'c' ] df.loc[df[ 'a' ]== 0 , 'e' ] = df[ 'd' ]end = time.time() 打印(结束 - 开始) ## 0.29007707595825195 秒
The vectorized operation takes 600 times faster compared to a python loop using if-else statements.
Solving Machine Learning/Deep Learning Networks
Deep learning requires us to solve multiple complex equations, and there are millions and millions of equations to solve. The billion-row problem. Running loops to solve these equations in Python is very slow and vectorization is the best solution.
For example, calculate the y-values for millions of rows in the following multiple linear regression equation:
We can vectorize instead of looping.
The values of m1, m2, m3... are determined by solving the above equation using millions of values corresponding to x1, x2, x3...
import numpy as np # 设置 m 的初始值 m = np.random.rand( 1 , 5 ) # 500 万行的输入值 x = np.random.rand( 5000000 , 5 )
## 使用循环 import numpy as np m = np.random.rand(1,5) x = np.random.rand(5000000,5) total = 0 tic = time.process_time() for i in range(0,5000000): total = 0 for j in range(0,5): total = total + x[i][j]*m[0][j] zer[i] = total toc = time.process_time() print ("Computation time = "+ str ((toc - tic)) + "seconds" ) ####计算时间 = 27.02 秒
## 矢量化 tic = time.process_time() #dot product np.dot(x,mT) toc = time.process_time() print ( "计算时间 = " + str ((toc - tic)) + "seconds" ) ####计算时间 = 0.107 秒
np.dot Implements vectorized matrix multiplication in the backend. It is 165 times faster compared to loops in Python.
Conclusion
Vectorization in python is very fast and should be preferred over loops whenever we are dealing with very large data sets.
# As you start implementing it over time, you will get used to thinking in terms of vectorization of your code.
The above is the detailed content of Using vectorization to replace loops in python. For more information, please follow other related articles on the PHP Chinese website!

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment