Chalk DataFrames
Calculate transaction totals, compare columns, and handle zero denominators.
Build a line total from unit price and quantity, then compare it with the authorized amount. A literal such as 100 applies to each row. Two column expressions read values from the same row.
Multiply two columns before converting cents to dollars. Name the intermediate value so later expressions can use it.
from chalk import _, functions as F
from chalkdf import DataFrame
tx = DataFrame({
"id": [1, 2, 3], "unit_cents": [125, 300, 75],
"units": [4, 2, 0], "authorized_cents": [500, 550, 0],
})
priced = tx.with_columns((_.unit_cents * _.units).alias("total_cents"))
priced.project({"id": _.id, "cents": _.total_cents, "dollars": _.total_cents / 100}).run()| # | idint64 | centsint64 | dollarsdouble |
|---|---|---|---|
| 1 | 1 | 500 | 5.0 |
| 2 | 2 | 600 | 6.0 |
| 3 | 3 | 0 | 0.0 |
Keeping cents in the intermediate result lets you compare two amounts in the same unit.
Calculate the signed difference and retain a boolean that identifies overcharges.
review = priced.project({
"id": _.id,
"difference": _.total_cents - _.authorized_cents,
"over_limit": _.total_cents > _.authorized_cents,
})
review.run()| # | idint64 | differenceint64 | over_limitbool |
|---|---|---|---|
| 1 | 1 | 0 | False |
| 2 | 2 | 50 | True |
| 3 | 3 | 0 | False |
Equality at the authorization limit produces false. To keep only rows that need review, use review.filter(_.over_limit).
Calculate the fraction of the authorization used. Use safe_divide to handle a zero authorization.
priced.project({
"id": _.id,
"fraction_used": F.safe_divide(_.total_cents.cast(float), _.authorized_cents),
}).run()| # | idint64 | fraction_useddouble |
|---|---|---|
| 1 | 1 | 1.0 |
| 2 | 2 | 1.0909090909090908 |
| 3 | 3 | null |
Here safe_divide returns null for the zero authorization. Keep the denominator in your output when downstream users need to distinguish it from missing inputs.
Translate the over-limit flag into a review amount. Retain the row for every transaction so the result can feed a later group summary.
review.project({
"id": _.id,
"to_review": F.if_then_else(_.over_limit, _.difference, 0),
}).run()| # | idint64 | to_reviewint64 |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 50 |
| 3 | 3 | 0 |
Only the excess 50 cents needs review on transaction 2. Keeping the other rows with a zero lets a downstream count include approved transactions.
An integer flag field can encode several checks on the same transaction. Mask the review bit before converting the result to a boolean.
flags = DataFrame({"flags": [0, 2, 3, None]})
flags.project({
"flags": _.flags,
"review": F.bitwise_and(_.flags, 2) != 0,
}).run()| # | flagsint64 | reviewbool |
|---|---|---|
| 1 | 0 | False |
| 2 | 2 | True |
| 3 | 3 | True |
| 4 | null | True |
Both 2 and 3 have the review bit set. A missing flag stays unknown.