0Pricing
Data Science Academy · 课时

按多个键分组

多级分组和结果索引

按多个键分组 是 CoddyKit 上的免费 Data Science Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Data Science Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Data Science Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Group on More Than One Column

Pass a list of keys to groupby and pandas forms a group for every unique combination of those columns.

df.groupby(["city", "year"])

Every Combo Is a Group

Two cities and three years can yield up to six groups, one per existing combination found in your data.

Aggregate Across Keys

Aggregation works exactly the same; the math just runs inside each combination instead of a single key.

df.groupby(["city", "year"])["sales"].sum()

Meet the MultiIndex

Grouping on several keys gives the result a MultiIndex, with one index level for each grouping column.

Read a MultiIndex Result

Each output row is labeled by a tuple like (city, year), so the index tells you exactly which group it is.

Select From a MultiIndex

Use loc with a tuple to pull one specific combination straight out of the grouped result.

result.loc[("Paris", 2024)]

Flatten With reset_index

Prefer flat columns? reset_index turns each index level back into an ordinary column you can filter.

result.reset_index()

Keep Empty Groups Out

By default pandas skips combinations with no rows, so your result shows only combinations that actually occur.

Order of Keys Matters

The key order you list sets the index level order, which changes how the result sorts and reads.

df.groupby(["year", "city"]).size()

Unstack for a Cross-Tab

Call unstack to lift one key into columns, turning a long grouped result into a readable grid.

result.unstack()

When to Use Several Keys

Reach for multi-key grouping whenever a question mentions two dimensions, like sales by city and by month.

Quick Check

You group by ["city", "year"]. What labels each result row?

Recap: Two Dimensions, One groupby

You can now slice data along several keys at once, read the MultiIndex, and reshape it for clear cross-tabs. 📊

常见问题解答

「按多个键分组」课时是免费的吗?

是的 — 「按多个键分组」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Data Science Academy 课程的其余内容,请升级到 CoddyKit PRO。 Data Science Academy 课程共包含 4 节课。

「按多个键分组」这节课中我会学到什么?

多级分组和结果索引 你通过在浏览器中直接运行的动手代码来练习 Data Science Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Data Science Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Data Science Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「按多个键分组」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Data Science Academy 课中编写并运行代码吗?

能。每节 Data Science Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 详解拆分—应用—合并
  2. 使用 agg 执行多种聚合
  3. 按多个键分组
  4. 使用 transform 创建分组特征
← 返回 Data Science Academy