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
- A single aggregate over a groupby gives one row per group.
as_index=Falsekeeps the key as a column instead of the index.sizecounts rows,nuniquecounts distinct values.
Keywords and builtins used here
asprint
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.
Step 1 of 5 in Grouping, step 14 of 26 in pandas.