Chalk DataFrames
Compose reusable predicates and decide which rows to retain when values are missing.
A review queue needs positive charges and a separate rule for refunds. Start by keeping the predicates as expressions. Inspecting them alongside their inputs makes it easier to check boundary and null cases before you discard rows.
Compare the threshold against values exactly on the boundary, below it, and missing.
from chalk import _, functions as F
from chalkdf import DataFrame
tx = DataFrame({
"id": [1, 2, 3, 4], "kind": ["charge", "charge", "refund", "charge"],
"amount": [10, 9, 4, None],
})
large = _.amount >= 10
tx.project({"id": _.id, "amount": _.amount, "large": large}).run()| # | idint64 | amountint64 | largebool |
|---|---|---|---|
| 1 | 1 | 10 | True |
| 2 | 2 | 9 | False |
| 3 | 3 | 4 | False |
| 4 | 4 | null | null |
The comparison is inclusive. A missing amount produces a null predicate.
Put parentheses around each comparison before combining them with & or |. Retain a charge at or above the threshold, or any refund.
needs_review = ((_.kind == "charge") & large) | (_.kind == "refund")
tx.filter(needs_review).run()| # | idint64 | kindstring | amountint64 |
|---|---|---|---|
| 1 | 1 | charge | 10 |
| 2 | 3 | refund | 4 |
The refund qualifies independently of its amount. Filtering preserves the input columns and keeps rows whose predicate evaluates to true.
If unreported amounts also require review, include that policy in the predicate.
tx.filter(needs_review | F.is_null(_.amount)).select("id", "kind").run()| # | idint64 | kindstring |
|---|---|---|
| 1 | 1 | charge |
| 2 | 3 | refund |
| 3 | 4 | charge |
ID 4 now appears in the queue. Using F.coalesce(_.amount, 0) >= 10 would instead treat its missing amount as below the threshold.
Sum the known charges for each kind, then apply a threshold to the resulting totals.
tx.filter(F.is_not_null(_.amount)).agg(
["kind"], _.amount.sum().alias("total")
).filter(_.total >= 15).run()| # | kindstring | totalint64 |
|---|---|---|
| 1 | charge | 19 |
Both charges contribute to the total of 19. Applying the threshold to individual input rows would discard them before they could be added together.
To count how many types of transaction have a qualifying amount, filter first and deduplicate the projected type. Counting the filtered rows alone would count purchases.
matches = tx.filter(_.amount >= 4).select("kind")
matches.distinct_on("kind").agg([], _.count().alias("distinct_kinds")).run()| # | distinct_kindsint64 |
|---|---|
| 1 | 2 |
The two charge rows contribute one kind. The refund contributes a second kind.
See missing data and DataFrame.filter.