dbt Analytics Engineering (50 Qs)•Part 2: Advanced Modeling, Incremental Builds & Macros (Mid-Level)
How do Python Models work in dbt?
mid LevelCode ExampledbtAdvanced Modeling
In Simple Words:
Starting in dbt 1.3+, models can be written in Python (.py) instead of SQL on platforms with native Python compute (Snowflake Snowpark, Databricks, BigQuery, PySpark).
- Ideal for data science, training ML models, text sentiment analysis, or complex statistical operations that are painful in SQL.
python
# models/marts/predict_churn.py
import pandas as pd
def model(dbt, session):
dbt.config(materialized="table")
# Read upstream dbt models as DataFrames
customers_df = dbt.ref("dim_customers").to_pandas()
# Apply ML / transformations
customers_df["risk_score"] = customers_df["total_spent"] / customers_df["days_active"]
return customers_df