typestar

transform and group-relative values in Python

transform returns a value per row, so it lines up with the original frame.

import pandas as pd

frame = pd.DataFrame({
    "lang": ["python", "python", "rust", "rust"],
    "tpm": [104, 91, 98, 88],
})

groups = frame.groupby("lang")["tpm"]
frame["group_mean"] = groups.transform("mean")
frame["share"] = (frame["tpm"] / groups.transform("sum")).round(3)
frame["rank_in_group"] = groups.rank(ascending=False).astype(int)

print(frame)

How it works

  1. agg collapses groups; transform broadcasts back.
  2. That is how you compute a share of the group total.
  3. rank inside a group numbers the rows within it.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
351
Tokens
132
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 3 of 5 in Grouping, step 16 of 26 in pandas.

← Previous Next →