Add each request's share of its user's tokens and its rank with groupby transform
Why it matters Per-row group features like share of total and rank within group are common model features and report columns.
To find which requests drive a user's bill you need, on every row, the share of that user's total and the rank inside the user. groupby().transform keeps one value per row, so the result lines up with the original table.
Write share_and_rank(df) where df has columns user_id (int) and tokens (int, at least one positive per user).
Return a DataFrame with columns exactly [user_id, tokens, share, rank_in_user] in the ORIGINAL row order and index, where share = tokens / (sum of that user's tokens) and rank_in_user is 1 for the user's largest request, 2 for the next, and so on (an int). Ties get different ranks in order of appearance: the earlier row gets the smaller rank.
def share_and_rank(df)Example
user_id [1, 1, 2], tokens [30, 10, 5] give share [0.75, 0.25, 1.0] and rank_in_user [1, 2, 1].
Understand the idea
groupby().agg reduces each group to one row. groupby().transform computes the same group statistic but returns it on EVERY row of the group, aligned to the original index. That lets you mix row values with group values in one line.
Worked example: user 1 has requests of 30 and 10 tokens. transform('sum') gives 40 on both rows, so shares are 30 / 40 = 0.75 and 10 / 40 = 0.25. User 2 has one request of 5, so its share is 5 / 5 = 1.0. Ranking within user from the largest: 30 is rank 1, 10 is rank 2.
Rule: share_i = x_i / sum of x over the group of i. rank_i = 1 + number of rows in the group that come before i in the sort order.
Feature engineering for churn and fraud models uses group shares and ranks, and so do cost breakdown reports.