Sub topic 2
Computing features from raw tables with Spark
Prerequisites and scope
This chapter assumes you can write basic PySpark DataFrame code, know what a Delta table is, and can run a Databricks notebook. It also assumes you know Unity Catalog's catalog.schema.table naming. The goal is to turn a raw event table into one row of features per entity. A later chapter stores those rows in a feature table.
From raw rows to one row per entity
Raw tables record events. An orders table has one row per order. A model that predicts churn needs one row per user. Feature computation closes that gap. You choose an entity (here, user_id), choose a window of history, and aggregate events into columns.
Three decisions shape every feature set:
- Grain. The grain is what one output row represents, such as one user or one product. Grain becomes the primary key of the feature table.
- Window. The window is how far back you look, such as 90 days. Name it in the column, for example
order_count_90d. - Aggregation. The aggregation is the function that collapses many events into one value: count, average, max, and so on.
A first aggregate feature set
The code below reads the orders table, keeps the last 90 days, and computes three features per user.
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
user_features_df = (
orders
.filter(F.col("order_ts") >= F.date_sub(F.current_date(), 90))
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.avg("amount").alias("avg_order_amount_90d"),
F.max("order_ts").alias("last_order_ts"),
)
)Reading it step by step:
spark.tableloads the Unity Catalog table lazily. Nothing runs yet.filterapplies the window.F.date_sub(F.current_date(), 90)is the date 90 days before today.groupBy("user_id")sets the grain.aggproduces one column per feature. Eachaliasnames the feature.
The result has the columns user_id, order_count_90d, avg_order_amount_90d, and last_order_ts. Because user_id is unique in the output, it can later serve as the primary key.
Naming features
Good names carry their meaning. Include the unit of the window (_90d) and what is being measured. Avoid names like feature1 or avg. Other people will find and reuse these columns, so a name should be understandable without opening the code.
Choosing aggregations
Different aggregations capture different behavior. A table of common choices:
| Goal | Spark function | Example feature |
|---|---|---|
| Activity level | `F.count`, `F.countDistinct` | `distinct_products_90d` |
| Typical size | `F.avg`, `F.expr("percentile_approx(...)")` | `median_order_amount_90d` |
| Total volume | `F.sum` | `total_spend_90d` |
| Recency | `F.max` on a timestamp | `last_order_ts` |
| Variability | `F.stddev` | `order_amount_stddev_90d` |
Recency is often better stated as a number. Convert last_order_ts into days_since_last_order. A number lets the model compare users directly, while a timestamp is tied to the date you computed it.
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
window_start = F.date_sub(F.current_date(), 90)
richer_features_df = (
orders
.filter(F.col("order_ts") >= window_start)
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.sum("amount").alias("total_spend_90d"),
F.avg("amount").alias("avg_order_amount_90d"),
F.countDistinct("product_id").alias("distinct_products_90d"),
F.max("order_ts").alias("last_order_ts"),
)
.withColumn(
"days_since_last_order",
F.datediff(F.current_date(), F.col("last_order_ts")),
)
.drop("last_order_ts")
)This example assumes orders has a product_id column.
Several windows in one pass
Models often benefit from short and long windows side by side, such as 7 and 90 days. Use conditional aggregation instead of running two separate queries. F.when returns null for rows outside the short window, and aggregate functions skip nulls.
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
in_7d = F.col("order_ts") >= F.date_sub(F.current_date(), 7)
in_90d = F.col("order_ts") >= F.date_sub(F.current_date(), 90)
multi_window_df = (
orders
.filter(in_90d)
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.count(F.when(in_7d, 1)).alias("order_count_7d"),
F.sum(F.when(in_7d, F.col("amount"))).alias("total_spend_7d"),
F.sum("amount").alias("total_spend_90d"),
)
)This scans the table once. The count(when(...)) pattern works because count ignores nulls, so only rows where the condition holds are counted.
Categorical features
Some features describe categories rather than numbers. You can aggregate a category into a count per value. A pivot turns each category into a column.
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
category_features_df = (
orders
.filter(F.col("order_ts") >= F.date_sub(F.current_date(), 90))
.groupBy("user_id")
.pivot("category", ["electronics", "grocery", "apparel"])
.agg(F.count("*"))
.na.fill(0)
.withColumnRenamed("electronics", "electronics_orders_90d")
.withColumnRenamed("grocery", "grocery_orders_90d")
.withColumnRenamed("apparel", "apparel_orders_90d")
)Pass the list of category values to pivot explicitly. Without it, Spark runs an extra job to discover the distinct values, and the output columns can change when new categories appear. A fixed list keeps the schema stable between runs, which matters once the output is written to a table. Encoding choices such as one-hot and scaling get their own chapter.
Joining sources
Features often come from more than one table. Compute each aggregate at the same grain, then join on the key. Joining aggregates is safer than joining raw rows, because joining raw tables first can multiply rows and inflate counts.
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
sessions = spark.table("main.web.sessions")
order_agg = (
orders.groupBy("user_id")
.agg(F.count("*").alias("order_count_90d"))
)
session_agg = (
sessions.groupBy("user_id")
.agg(F.count("*").alias("session_count_90d"))
)
combined_df = (
order_agg.join(session_agg, on="user_id", how="full_outer")
.na.fill(0, subset=["order_count_90d", "session_count_90d"])
)Use a full outer join if you want every user seen in either source. A user with sessions but no orders gets nulls from the orders side. Filling counts with 0 is correct here, because no events means a count of zero. For averages, a null often means "unknown" and should not be filled with 0 without thought.
Edge cases and common errors
- Empty windows. Users with no events in the window do not appear in a
groupByoutput at all. If you need a row for every user, left-join the aggregates onto a user table and fill counts with 0. - Non-deterministic windows.
F.current_date()changes each day. Re-running the same code tomorrow gives different values. This is expected for fresh features, but it makes training runs hard to reproduce. For training data, compute features as of a fixed date, and see the chapter on point-in-time correctness. - Leakage. If a label is "churned in the next 30 days," features must only use events before the prediction date. A window that reaches past that date leaks the answer into the features.
- Duplicate keys. The output of
groupBy("user_id")has unique keys. A join that fans out rows can break that. Check uniqueness before writing a feature table. - Null keys. Rows with a null
user_idform their own group. Primary keys cannot be null, so filter them out. - Skew. A few very active entities can produce uneven partitions. Adaptive query execution in Databricks handles most cases. Check the Spark UI if one task runs far longer than the others.
A quick uniqueness and null check before moving on:
from pyspark.sql import functions as F
total = user_features_df.count()
distinct_keys = user_features_df.select("user_id").distinct().count()
null_keys = user_features_df.filter(F.col("user_id").isNull()).count()
assert total == distinct_keys, "user_id is not unique"
assert null_keys == 0, "user_id contains nulls"Putting it together
A reusable function applies the tips above. It takes an as-of date, computes features, drops null keys, and returns a DataFrame ready to be written to a feature table.
from pyspark.sql import DataFrame, functions as F
def compute_user_features(orders: DataFrame, as_of_date: str, days: int = 90) -> DataFrame:
as_of = F.to_date(F.lit(as_of_date))
window_start = F.date_sub(as_of, days)
return (
orders
.filter(F.col("user_id").isNotNull())
.filter((F.col("order_ts") >= window_start) & (F.col("order_ts") < as_of))
.groupBy("user_id")
.agg(
F.count("*").alias(f"order_count_{days}d"),
F.avg("amount").alias(f"avg_order_amount_{days}d"),
F.max("order_ts").alias("last_order_ts"),
)
)
features_df = compute_user_features(spark.table("main.sales.orders"), "2026-12-01")The upper bound order_ts < as_of excludes events on or after the as-of date, which guards against leakage.
Exercise
Your 90-day features are computed with F.current_date(). A teammate re-runs the training notebook a week later and gets different feature values and a different model. Why does this happen, and how would you change the code?
Show answer
F.currentdate() moves forward each day, so the 90-day window covers different orders on each run. Change the code to take an explicit as-of date (for example a function parameter), filter with orderts >= asof - 90 days and orderts < as_of, and record that date with the training run. The same date then produces the same features and avoids using events after the prediction point.
Exercise
You join the raw orders table to the raw sessions table on userid and then run groupBy("userid").agg(F.count("*")). The order counts are far too high. What went wrong, and what is the fix?
Show answer
Joining raw rows fans out the data. A user with 5 orders and 20 sessions produces 100 joined rows, so count("*") returns 100 instead of 5. Aggregate each table to one row per user first, then join the aggregates on user_id.