Chalk DataFrames
Choose grouping keys, count observations, and compute weighted summaries.
For a purchase summary, first decide what one result row represents. Group by shopper to summarize accounts, or by both shopper and channel to expose differences across channels.
Name each measure so you can sort, filter, or project it later. Count rows and observed amounts separately.
from chalk import _, functions as F
from chalkdf import DataFrame
tx = DataFrame({
"user": ["a", "a", "a", "b"], "channel": ["web", "web", "store", "web"],
"units": [1, 3, 1, 2], "spent": [10, 18, None, 16],
})
measured = tx.with_columns(F.is_not_null(_.spent).cast(int).alias("observed"))
measured.agg(
["user"], _.count().alias("purchases"),
_.observed.sum().alias("priced"), _.spent.sum().alias("total"),
).order_by("user").run()| # | userstring | purchasesint64 | pricedint64 | totalint64 |
|---|---|---|---|---|
| 1 | a | 3 | 2 | 28 |
| 2 | b | 1 | 1 | 16 |
Shopper a has three purchases and two recorded amounts. Distinguishing the two counts makes the total easier to interpret.
Add channel to the key to get a separate result for each observed shopper and channel combination.
tx.agg(
["user", "channel"], _.count().alias("purchases"),
).order_by("user", "channel").run()| # | userstring | channelstring | purchasesint64 |
|---|---|---|---|
| 1 | a | store | 1 |
| 2 | a | web | 2 |
| 3 | b | web | 1 |
The store purchase now has its own row. Sort the result explicitly when presentation order matters.
Exclude rows without a recorded spend before summing both spend and units. Divide the two totals after grouping.
priced = tx.filter(F.is_not_null(_.spent))
totals = priced.agg(["user"], _.spent.sum().alias("spent"), _.units.sum().alias("units"))
totals.project({
"user": _.user, "unit_price": F.safe_divide(_.spent.cast(float), _.units),
}).order_by("user").run()| # | userstring | unit_pricedouble |
|---|---|---|
| 1 | a | 7.0 |
| 2 | b | 8.0 |
Shopper a paid 28 for four priced units. Averaging the two purchase-level unit prices would give the smaller purchase the same weight as the larger one.
Pass an empty list of grouping keys to produce a single summary for the priced transactions.
priced.agg([], _.count().alias("purchases"), _.spent.sum().alias("total")).run()| # | purchasesint64 | totalint64 |
|---|---|---|
| 1 | 3 | 44 |
Use a window when you need a group-derived value alongside each individual input row.
Count every purchase while totaling only web spend. Filtering the input would also remove store purchases from the count.
tx.agg(
["user"],
_.count().alias("all_purchases"),
F.if_then_else(_.channel == "web", _.spent, 0).sum().alias("web_spend"),
).order_by("user").run()| # | userstring | all_purchasesint64 | web_spendint64 |
|---|---|---|---|
| 1 | a | 3 | 28 |
| 2 | b | 1 | 16 |
The store purchase contributes to the count for shopper a. Its contribution to web spend is zero.
See window functions and DataFrame.agg.