typestar

groupby in Python

Split by a key, apply a function, combine the answers.

import pandas as pd

frame = pd.DataFrame({
    "lang": ["python", "python", "rust", "rust", "sql"],
    "stars": [3, 1, 3, 2, 2],
    "tpm": [104, 91, 98, 88, 79],
})

print(frame.groupby("lang")["tpm"].mean().round(1))
print(frame.groupby("lang").size())
print(frame.groupby("lang", as_index=False)["stars"].max())

How it works

  1. A single aggregate over a groupby gives one row per group.
  2. as_index=False keeps the key as a column instead of the index.
  3. size counts rows, nunique counts distinct values.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
304
Tokens
135
Three-star pace
110 tpm

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

Type this snippet

Step 1 of 5 in Grouping, step 14 of 26 in pandas.

← Previous Next →