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.

​
Summarize by one key

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
1a3228
2b1116

Shopper a has three purchases and two recorded amounts. Distinguishing the two counts makes the total easier to interpret.

​
Group on multiple keys

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
1astore1
2aweb2
3bweb1

The store purchase now has its own row. Sort the result explicitly when presentation order matters.

​
Calculate a weighted unit price

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
1a7.0
2b8.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.

​
Summarize the entire input

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
1344

Use a window when you need a group-derived value alongside each individual input row.

​
Condition one measure within a group

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
1a328
2b116

The store purchase contributes to the count for shopper a. Its contribution to web spend is zero.

See window functions and DataFrame.agg.