transforming-data
This Claude Code skill provides patterns and implementations for transforming raw data into analytical datasets using ETL/ELT approaches, dbt SQL models, Python DataFrame libraries (pandas, polars, PySpark), and workflow orchestration tools like Airflow. Use it when designing data pipelines, building incremental dbt models, optimizing pandas code with polars, or setting up production-ready transformations with testing and quality validation.
git clone --depth 1 https://github.com/ancoleman/ai-design-components /tmp/transforming-data && cp -r /tmp/transforming-data/skills/transforming-data ~/.claude/skills/transforming-dataSKILL.md
# Data Transformation
Transform raw data into analytical assets using modern transformation patterns, frameworks, and orchestration tools.
## Purpose
Select and implement data transformation patterns across the modern data stack. Transform raw data into clean, tested, and documented analytical datasets using SQL (dbt), Python DataFrames (pandas, polars, PySpark), and pipeline orchestration (Airflow, Dagster, Prefect).
## When to Use
Invoke this skill when:
- Choosing between ETL and ELT transformation patterns
- Building dbt models (staging, intermediate, marts)
- Implementing incremental data loads and merge strategies
- Migrating pandas code to polars for performance improvements
- Orchestrating data pipelines with dependencies and retries
- Adding data quality tests and validation
- Processing large datasets with PySpark
- Creating production-ready transformation workflows
## Quick Start: Common Patterns
### dbt Incremental Model
```sql
{{
config(
materialized='incremental',
unique_key='order_id'
)
}}
select order_id, customer_id, order_created_at, sum(revenue) as total_revenue
from {{ ref('int_order_items_joined') }}
group by 1, 2, 3
{% if is_incremental() %}
where order_created_at > (select max(order_created_at) from {{ this }})
{% endif %}
```
### polars High-Performance Transformation
```python
import polars as pl
result = (
pl.scan_csv('large_dataset.csv')
.filter(pl.col('year') == 2024)
.with_columns([(pl.col('quantity') * pl.col('price')).alias('revenue')])
.group_by('region')
.agg(pl.col('revenue').sum())
.collect() # Execute lazy query
)
```
### Airflow Data Pipeline
```python
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
with DAG(
dag_id='daily_sales_pipeline',
schedule_interval='0 2 * * *',
default_args={'retries': 2, 'retry_delay': timedelta(minutes=5)},
start_date=datetime(2024, 1, 1),
catchup=False
) as dag:
extract = PythonOperator(task_id='extract', python_callable=extract_data)
transform = PythonOperator(task_id='transform', python_callable=transform_data)
extract >> transform
```
## Decision Frameworks
### ETL vs ELT Selection
**Use ELT (Extract, Load, Transform)** when:
- Using modern cloud data warehouse (Snowflake, BigQuery, Databricks)
- Transformation logic changes frequently
- Team includes SQL analysts
- Data volume 10GB-1TB+ (leverage warehouse parallelism)
**Tools**: dbt, Dataform, Snowflake tasks, BigQuery scheduled queries
**Use ETL (Extract, Transform, Load)** when:
- Regulatory compliance requires pre-load data redaction (PII/PHI)
- Target system lacks compute power
- Real-time streaming with immediate transformation
- Legacy systems without cloud warehouse
**Tools**: AWS Glue, Azure Data Factory, custom Python scripts
**Use Hybrid** when combining sensitive data cleansing (ETL) with analytics transformations (ELT).
**Default recommendation**: ELT with dbt unless specific compliance or performance constraints require ETL.
For detailed patterns, see `references/etl-vs-elt-patterns.md`.
### DataFrame Library Selection
**Choose pandas** when:
- Data size < 500MB
- Prototyping or exploratory analysis
- Need compatibility with pandas-only libraries
**Choose polars** when:
- Data size 500MB-100GB
- Performance critical (10-100x faster than pandas)
- Production pipelines with memory constraints
- Want lazy evaluation with query optimization
**Choose PySpark** when:
- Data size > 100GB
- Need distributed processing across cluster
- Existing Spark infrastructure (EMR, Databricks)
**Migration path**: pandas → polars (easier, similar API) or pandas → PySpark (requires cluster)
For comparisons and migration guides, see `references/dataframe-comparison.md`.
### Orchestration Tool Selection
**Choose Airflow** when:
- Enterprise production (proven at scale)
- Need 5,000+ integrations
- Managed services available (AWS MWAA, GCP Cloud Composer)
**Choose Dagster** when:
- Heavy dbt usage (native `dbt_assets` integration)
- Data lineage and asset-based workflows prioritized
- ML pipelines requiring testability
**Choose Prefect** when:
- Dynamic workflows (runtime task generation)
- Cloud-native architecture preferred
- Pythonic API with decorators
**Safe default**: Airflow (battle-tested) unless specific needs for Dagster/Prefect.
For detailed patterns, see `references/orchestration-patterns.md`.
## SQL Transformations with dbt
### Model Layer Structure
1. **Staging Layer** (`models/staging/`)
- 1:1 with source tables
- Minimal transformations (renaming, type casting, basic filtering)
- Materialized as views or ephemeral
2. **Intermediate Layer** (`models/intermediate/`)
- Business logic and complex joins
- Not exposed to end users
- Often ephemeral (CTEs only)
3. **Marts Layer** (`models/marts/`)
- Final models for reporting
- Fact tables (events, transactions)
- Dimension tables (customers, products)
- Materialized as tables or incremental
### dbt Materialization Types
**View**: Query re-run each time model referenced. Use for fast queries, staging layer.
**Table**: Full refresh on each run. Use for frequently queried models, expensive computations.
**Incremental**: Only processes new/changed records. Use for large fact tables, event logs.
**Ephemeral**: CTE only, not persisted. Use for intermediate calculations.
### dbt Testing
```yaml
models:
- name: fct_orders
columns:
- name: order_id
tests:
- unique
- not_null
- name: customer_id
tests:
- relationships:
to: ref('dim_customers')
field: customer_id
- name: total_revenue
tests:
- dbt_utils.accepted_range:
min_value: 0
```
For comprehensive dbt patterns, see:
- `references/dbt-best-practices.md`
- `references/incremental-strategies.md`
## Python DataFrame TransformationManage Linux systems covering systemd services, process management, filesystems, networking, performance tuning, and troubleshooting. Use when deploying applications, optimizing server performance, diagnosing production issues, or managing users and security on Linux servers.
Data pipelines, feature stores, and embedding generation for AI/ML systems. Use when building RAG pipelines, ML feature serving, or data transformations. Covers feature stores (Feast, Tecton), embedding pipelines, chunking strategies, orchestration (Dagster, Prefect, Airflow), dbt transformations, data versioning (LakeFS), and experiment tracking (MLflow, W&B).
Strategic guidance for designing modern data platforms, covering storage paradigms (data lake, warehouse, lakehouse), modeling approaches (dimensional, normalized, data vault, wide tables), data mesh principles, and medallion architecture patterns. Use when architecting data platforms, choosing between centralized vs decentralized patterns, selecting table formats (Iceberg, Delta Lake), or designing data governance frameworks.
Design cloud network architectures with VPC patterns, subnet strategies, zero trust principles, and hybrid connectivity. Use when planning VPC topology, implementing multi-cloud networking, or establishing secure network segmentation for cloud workloads.
Design comprehensive security architectures using defense-in-depth, zero trust principles, threat modeling (STRIDE, PASTA), and control frameworks (NIST CSF, CIS Controls, ISO 27001). Use when designing security for new systems, auditing existing architectures, or establishing security governance programs.
Assembles component outputs from AI Design Components skills into unified, production-ready component systems with validated token integration, proper import chains, and framework-specific scaffolding. Use as the capstone skill after running theming, layout, dashboard, data-viz, or feedback skills to wire components into working React/Next.js, Python, or Rust projects.
Builds AI chat interfaces and conversational UI with streaming responses, context management, and multi-modal support. Use when creating ChatGPT-style interfaces, AI assistants, code copilots, or conversational agents. Handles streaming text, token limits, regeneration, feedback loops, tool usage visualization, and AI-specific error patterns. Provides battle-tested components from leading AI products with accessibility and performance built in.
Constructs secure, efficient CI/CD pipelines with supply chain security (SLSA), monorepo optimization, caching strategies, and parallelization patterns for GitHub Actions, GitLab CI, and Argo Workflows. Use when setting up automated testing, building, or deployment workflows.