Sample Python ETL Script: Ultimate Guide with Downloadable Code Examples

In the realm of data engineering, Extract, Transform, Load (ETL) scripts play a pivotal role in integrating and transforming data from various sources. Python, with its robust ecosystem and simplicity, is a popular choice for writing ETL scripts. Let's delve into a sample Python ETL script, exploring its components, and understanding its functionality.

🐍 Python elif Statement Explained | Conditional Statements Made Easy
🐍 Python elif Statement Explained | Conditional Statements Made Easy

Our sample script will use the pandas library for data manipulation, SQLAlchemy to connect to databases, and NumPy for numerical operations. We'll be retrieving data from a SQLite database, performing transformations, and then loading it into a CSV file.

an image of a programming program with the words quick python scripting and instructions on it
an image of a programming program with the words quick python scripting and instructions on it

Setting Up the Environment

The first step in our ETL process is setting up the environment. We'll import the necessary libraries and establish a connection to our database.

the if statement in python is true or false, and it's very easy to read
the if statement in python is true or false, and it's very easy to read

Here's a simple example:

```python import pandas as pd from sqlalchemy import create_engine # Establish a database connection engine = create_engine('sqlite:///example.db') ```

Extracting Data

python aesthetic
python aesthetic

The 'Extract' phase involves retrieving data from the source. In our case, we're using SQLAlchemy's create_engine and pd.read_sql_query functions to extract data from our SQLite database.

Let's see how we can extract data from a table named 'sales':

```python # Extract data query = "SELECT * FROM sales" df = pd.read_sql_query(query, engine) ```

Transforming Data

a screenshot of a computer screen with the words python string method in front of it
a screenshot of a computer screen with the words python string method in front of it

In the 'Transform' phase, we manipulate the extracted data to fit our required schema. This could involve data cleaning, aggregations, merges, or pivoting. Let's perform a simple transformation - calculating the total sales amount.

Here's how we can do this using pandas:

```python # Transform data df['total_sales'] = (df['quantity'] * df['price']).sum() ```

Transforming Data Further

Master Data Export in Python – One Cheat Sheet to Rule Them All!
Master Data Export in Python – One Cheat Sheet to Rule Them All!

We can further transform our data by aggregating it by a certain category, say 'region'. Here's how we can do this:

```python # Transform data further df_agg = df.groupby('region')['total_sales'].sum() ```

Loading Data

25+ Examples of Real Python Programming Code - Skillcrush
25+ Examples of Real Python Programming Code - Skillcrush
an image of a computer screen with many lines and numbers on the bottom half of it
an image of a computer screen with many lines and numbers on the bottom half of it
Python Conditional Statements Cheat Sheet
Python Conditional Statements Cheat Sheet
a screenshot of a computer screen with the text looping through dictionaries in python
a screenshot of a computer screen with the text looping through dictionaries in python
Python Unit 4 Cheat Sheet 🐍 | Lists, Tuples, Dictionary & Set (AKTU)
Python Unit 4 Cheat Sheet 🐍 | Lists, Tuples, Dictionary & Set (AKTU)
Python type casting cheat sheet
Python type casting cheat sheet
an image of a computer screen with text and numbers on it, including the same language as
an image of a computer screen with text and numbers on it, including the same language as
Python Implementation of Min-Heap with Insert, Pop, and Peek Operations
Python Implementation of Min-Heap with Insert, Pop, and Peek Operations
🐍 Python List Methods Cheat Sheet ✨
🐍 Python List Methods Cheat Sheet ✨
the if statement in python is used to execute a block of code information for example
the if statement in python is used to execute a block of code information for example
Top Open Source Tools to Explore
Top Open Source Tools to Explore
a black screen with text that reads 12 python scripts to organize your daily workflow
a black screen with text that reads 12 python scripts to organize your daily workflow
Enumeration in Python
Enumeration in Python
🐍 Python – if-else Statement (Complete Beginner Guide)
🐍 Python – if-else Statement (Complete Beginner Guide)
Python if elif else Statement with Example Programs - EasyCodeBook.com
Python if elif else Statement with Example Programs - EasyCodeBook.com
Python tkinter Toolbox
Python tkinter Toolbox
Python Lists Explained: Complete Beginner Cheat Sheet
Python Lists Explained: Complete Beginner Cheat Sheet
🐍 Python If-Else Statement Cheat Sheet | Learn Decision Making in Python 🚀
🐍 Python If-Else Statement Cheat Sheet | Learn Decision Making in Python 🚀
Yield Statement
Yield Statement
a screenshot of a web page with text and an image of a snake on it
a screenshot of a web page with text and an image of a snake on it

The final 'Load' phase involves storing the transformed data into our target system. In our example, we're loading the data into a CSV file using pandas' to_csv function.

The following code will save our dataframe 'df_agg' to a CSV file:

```python # Load data df_agg.to_csv('output.csv', index=False) ```

Now that we've walked through a basic Python ETL script, it's time to expand your learnings. Experiment with different data sources, transformations, and output targets to tailor your ETL scripts to your specific needs. Happy scripting!

Related Articles

Sample Lambda Python Function Python Code To Read An Excel Long Python Code Example Sample In Random Python Lstm Sample Code Pytorch Python Web Login Page Example Python Example Code For Loop Sample Python Etl Script Python Code To Call Rest Api With Basic Authentication Python Turtle Code Github