Price API requests with marginal token tiers using vectorized NumPy instead of apply
Why it matters Vectorized column math is often 50 to 100 times faster than row-wise apply, which matters on large usage logs.
A pricing sheet charges tokens in marginal tiers, like income tax: the first tokens of a request at one rate, the next at a lower rate. Writing this with df.apply and if statements is slow on millions of rows; np.clip does it on whole columns.
Write tier_costs(df) where df has an int column tokens (>= 0). Prices per 1000 tokens, applied marginally per request:
- tokens 1 to 1000: 1.0
- tokens 1001 to 10000: 0.8
- tokens above 10000: 0.5
Return a list of floats, the cost of each request in row order. Use vectorized column math, no Python loop over rows.
def tier_costs(df)Example
tokens [500, 3000, 20000] give [0.5, 2.6, 13.2].
Understand the idea
Vectorized code applies one operation to a whole column at once in compiled code, instead of calling a Python function per row. df.apply(f, axis=1) is a hidden Python loop; NumPy functions like np.clip, np.where and np.select run over the whole array.
Worked example: a 3000-token request. Tier 1 takes the first 1000 tokens: 1000 * 1.0 = 1000. Tier 2 takes the next 2000: 2000 * 0.8 = 1600. Tier 3 gets 0. Total = 2600 per 1000 tokens, so the cost is 2.6.
Rule for a marginal tier from a to b: tokens_in_tier = clip(t - a, 0, b - a). cost = sum over tiers of rate * tokens_in_tier / 1000.
Billing jobs, feature engineering on large logs and data cleaning all use vectorized column math instead of apply.