Data Transformation
Transformations can be applied at various times in the data lifecycle. For example, an API will usually apply transformations on the server-side, before you (the host) receives the data. You might apply transformations immediately before storing, and then again at query-time while doing analytics.
This Lesson Will Cover
- 🔄 Data transformation fundamentals and importance
- 🗃️ SQL-based transformations with practical examples
- 🚀 Apache Spark transformations for large-scale data
- 🧹 Data cleaning and standardization techniques
- 📊 Calculating key business metrics
- ✅ Data quality validation methods
- 🌍 Real-world transformation workflows
Why Is Data Transformation Important?
Data transformations convert raw data into a format that’s useful for analysis, reporting, and decision-making. They are also used to identify and fix data quality issues.
- Consistency: Converting data into standardized formats to ensure compatibility across systems and processes.
- Accuracy: Cleaning and validating data to ensure reliable insights and decision-making.
- Relevance: Structuring data to answer specific business questions and meet organizational needs.
Transformation Use Cases
Common transformations include:
- Filtering: Removing irrelevant rows based on conditions.
- Aggregations: Summing, averaging, or counting data to extract high-level insights.
- Joins: Combining multiple tables to create enriched datasets.
- Derived Columns: Creating new features based on existing data (e.g., calculating age from a birth date).
SQL
SQL (Structured Query Language) is a powerful tool for querying and transforming structured data stored in relational databases or data warehouses.
Example Transformation: Rolling Sum
Imagine a retail dataset with the following structure:
| CustomerID | OrderDate | OrderAmount |
|---|---|---|
| 123 | 2024-11-01 | 250.50 |
| 124 | 2024-11-01 | 175.25 |
| 125 | 2024-11-02 | 100.00 |
| 126 | 2024-11-02 | 325.75 |
| 127 | 2024-11-03 | 450.00 |
| 128 | 2024-11-03 | 225.50 |
Goal: Calculate daily revenue and running total for November 2024.
Here’s how we can do this with PostgreSQL:
SELECT
OrderDate,
SUM(OrderAmount) AS DailyRevenue,
SUM(SUM(OrderAmount)) OVER (
ORDER BY OrderDate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS RunningTotal
FROM
Orders
WHERE
OrderDate BETWEEN '2024-11-01' AND '2024-11-30'
GROUP BY
OrderDate
ORDER BY
OrderDate;
Result:
| OrderDate | DailyRevenue | RunningTotal |
|---|---|---|
| 2024-11-01 | 425.75 | 425.75 |
| 2024-11-02 | 425.75 | 851.50 |
| 2024-11-03 | 675.50 | 1527.00 |
In this example, we generated a feature named RunningTotal that can provide insights into revenue growth patterns for forecasting models and reporting.
Apache Spark
Apache Spark is a distributed computing framework for processing large-scale data during ingestion.
Example Transformation: Rolling Sum
Let’s do the same example as above using Spark.
Imagine the same retail dataset in a source system:
| CustomerID | Date | Amount |
|---|---|---|
| 123 | 20241101 | 250.50 |
| 124 | 20241101 | 175.25 |
| 125 | 20241102 | 100.00 |
| 126 | 20241102 | 325.75 |
| 127 | 20241103 | 450.00 |
| 128 | 20241103 | 225.50 |
Goal: Transform and calculate daily revenue and running total for November 2024. Importantly, we do not want to use the source system to do the transformation. We’re going to offload that compute onto a Spark cluster.
from pyspark.sql import Window
from pyspark.sql.functions import sum, to_date, col, date_format
# Create window specification for running total
window_spec = Window.orderBy('OrderDate').rowsBetween(Window.unboundedPreceding, 0)
# Transform the data
result_df = (source_df
.withColumn('OrderDate', to_date(col('Date'), 'yyyyMMdd'))
.groupBy('OrderDate')
.agg(sum('Amount').alias('DailyRevenue'))
.withColumn('RunningTotal', sum('DailyRevenue').over(window_spec))
.orderBy('OrderDate')
)
# Write the results to a SQL table
result_df.write \
.mode("overwrite") \
.format("jdbc") \
.option("url", f"jdbc:postgresql://{os.getenv('DB_HOST')}:5432/analytics") \
.option("dbtable", 'daily_revenue') \
.option("user", os.getenv('DB_USER')) \
.option("password", os.getenv('DB_PASSWORD')) \
.save()
Result:
| OrderDate | DailyRevenue | RunningTotal |
|---|---|---|
| 2024-11-01 | 425.75 | 425.75 |
| 2024-11-02 | 425.75 | 851.50 |
| 2024-11-03 | 675.50 | 1527.00 |
Our Spark job loads the result into a new SQL table in our analytics database.
Data Cleaning and Standardization
Let’s look at actual examples of cleaning and standardizing data using BigQuery.
Cleaning Data
Data cleaning involves identifying and correcting errors and inconsistencies in your dataset.
Common techniques include:
- Handling Missing Values: Filling in gaps with default values, averages, or predictions.
UPDATE orders
SET
email = COALESCE(email, 'unknown@example.com'), -- Replace missing emails with unknown@example.com
purchase_amount = IFNULL(purchase_amount, ( -- Replace missing purchase amount with average
SELECT AVG(purchase_amount) FROM orders
))
WHERE TRUE; -- Apply to all rows
- Removing Duplicates: Ensuring no redundant rows exist.
WITH numbered_rows AS ( -- Identify duplicated rows
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY order_id, customer_id, order_date, purchase_amount -- All dimensions
ORDER BY order_id
) as row_num
FROM orders
)
SELECT COUNT(*) -- Get count of rows that have been duplicated
FROM numbered_rows
WHERE row_num > 1;
- Correcting Errors: Fixing typos, invalid entries, or inconsistent formats.
UPDATE customers
SET state = CASE
WHEN LOWER(state) IN ('ca', 'california', 'califorina') THEN 'CA'
WHEN LOWER(state) IN ('ny', 'new york', 'newyork') THEN 'NY'
ELSE UPPER(state)
END
WHERE TRUE; -- Apply to all rows
Standardization
Standardization ensures that data adheres to uniform rules for easier analysis. Examples include:
- Date Formats: Converting all date fields to a consistent format (e.g., YYYY-MM-DD).
INSERT INTO
orders_by_date
SELECT
order_id,
CASE
WHEN REGEXP_CONTAINS(date_field, r'^\d{4}-\d{2}-\d{2}$')
THEN PARSE_DATE('%Y-%m-%d', date_field)
WHEN REGEXP_CONTAINS(date_field, r'^\d{2}/\d{2}/\d{4}$')
THEN PARSE_DATE('%m/%d/%Y', date_field)
WHEN REGEXP_CONTAINS(date_field, r'^\d{8}$')
THEN PARSE_DATE('%Y%m%d', date_field)
ELSE NULL
END as parsed_date
FROM orders;
- Units of Measurement: Standardizing units (e.g., converting all weights to kilograms).
UPDATE products
SET weight = CASE
WHEN weight_unit = 'LBS' THEN weight * 0.45359237
WHEN weight_unit = 'OZ' THEN weight * 0.0283495
END,
weight_unit = 'KG'
WHERE weight_unit IN ('LBS', 'OZ');
- Case Formatting: Ensuring consistent capitalization (e.g., “New York” vs “new york”).
UPDATE customers
SET
city = INITCAP(city),
country_code = UPPER(country_code),
email = LOWER(email)
WHERE TRUE;
Calculating Key Metrics
Metrics provide actionable insights and are often used as features in AI models. Examples include:
- CLV (Customer Lifetime Value): Calculated as the sum of all purchases by a customer.
SELECT
customer_id,
SUM(purchase_amount) as lifetime_value,
COUNT(DISTINCT order_id) as total_orders,
SUM(purchase_amount) / COUNT(DISTINCT order_id) as avg_order_value
FROM orders
GROUP BY customer_id;
- Churn Rate: Percentage of customers lost over a given period.
WITH active_customers AS (
SELECT DISTINCT
customer_id,
DATE_TRUNC(order_date, MONTH) as month
FROM orders
)
SELECT
current_month.month,
1.0 - COUNT(next_month.customer_id) / COUNT(current_month.customer_id) as churn_rate
FROM active_customers current_month
LEFT JOIN active_customers next_month
ON current_month.customer_id = next_month.customer_id
AND next_month.month = DATE_ADD(current_month.month, INTERVAL 1 MONTH)
GROUP BY current_month.month
ORDER BY current_month.month;
- AOV (Average Order Value): Total revenue divided by the number of orders.
SELECT
DATE_TRUNC(order_date, MONTH) as month,
SUM(purchase_amount) / COUNT(DISTINCT order_id) as aov,
SUM(purchase_amount) as total_revenue,
COUNT(DISTINCT order_id) as total_orders
FROM orders
GROUP BY month
ORDER BY month;
Quality Validation
When to Validate Data?
Errors at any step in a data pipeline can propagate downstream, leading to incorrect calculations, poorly trained models, and generally bad outcomes from AI.
Validation should be done often to ensure that data meets quality standards before being used. Ideally, at each stage of the pipeline - during ingestion, after transformations, and before using it for analysis or model training.
Common Validation Techniques
-
Range Checks:
- Verify numerical fields fall within expected ranges (e.g., a customer age cannot be negative).
-
Uniqueness Constraints:
- Ensure key fields (e.g., CustomerID) are unique.
-
Cross-Field Validation:
- Check consistency across related fields (e.g., OrderDate cannot be later than DeliveryDate).
-
Distribution Analysis:
- Compare distributions in the data to expected patterns to identify anomalies.
Real-World Workflow: End-to-End Transformation
Imagine you’re building an AI model to recommend products for an e-commerce platform. Here’s how transformation steps might look:
-
SQL Filtering and Aggregation:
- Filter out orders with missing customer IDs or invalid dates.
- Aggregate total spending for each customer.
-
Cleaning and Standardization:
- Handle missing order amounts by imputing the average value.
- Standardize all prices to the same currency.
-
Feature Engineering:
- Create new metrics, such as “average days between purchases.”
-
Validation:
- Ensure all calculated metrics fall within logical ranges.
The resulting dataset is clean, structured, and enriched—ready for training your AI model.
Conclusion
I can clearly remember the first time I transformed data. I was playing hockey (as one does, in Canada) as the goalie, and I would track my saves and goals against for each game in a spreadsheet. The transformation I did was to add a calculated column for “save percentage”.
Yup. I’ve always loved working with data.
I think that everyone should lean into the things that they loved doing as a kid.
Key Takeaways
🔄 Data transformation is essential for converting raw data into analysis-ready formats.
🛠️ SQL and Apache Spark provide powerful tools for data transformation at different scales.
📊 Common transformations include filtering, aggregation, joins, and feature engineering.
✅ Regular validation checks help ensure data accuracy throughout the pipeline.
🔗 Real-world transformations often combine multiple techniques in a sequential workflow.
Next: Data Delivery
The whole idea of ingesting and transforming data, like we’ve been discussing, is to make it available to someone.
That’s what the next section, data access and delivery, is all about.
Comments (0)
No comments yet.