Using groupby with a MultiIndex

Let's explore how the groupby function works for hierarchically indexed data.

To start with, we can assign two indices to the sample sales data, as shown:

multiindex_df = sales_data.set_index(["ShipMode", "Category"])multiindex_df.head()

The following will be the output:

Snapshot of multi-indexed data

Grouping by an index can be done by specifying either the level number or the index name:

multiindex_df.groupby(level = 0).sum()

The following will be the output:

The level attribute of groupby

The level parameter ...

Get Mastering pandas - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.