Represent hierarchical categories
A DataFrame needs labels such as region and team on its rows.
Pandas · Class
pandas.MultiIndex is a hierarchical index that uses multiple levels of labels on one Series or DataFrame axis. It supports indexing by combinations of keys while keeping the underlying object at its usual dimensionality.
MultiIndex is pandas' hierarchical index for labeling one axis with multiple levels. Each row label is represented by a unique combination of level labels, allowing DataFrames and Series to be indexed along several dimensions without adding dimensions to the object.
class pandas.MultiIndex(*levels=None*, *codes=None*, *sortorder=None*, *names=None*, *copy=False*, *name=None*, *verify_integrity=True*)[source]| Name | Type | Description |
|---|---|---|
levels | sequence of arrays | The unique labels for each level. |
codes | sequence of arrays | Integers for each level designating which label occurs at each position. |
sortorder | optional int | Level of sortedness; it must be lexicographically sorted by that level. |
names | optional sequence of objects | Names for the index levels; name is accepted for compatibility. |
copy | bool, default False | Whether to copy metadata. |
name | optional hashable | Compatibility alias for names. |
verify_integrity | bool, default True | Whether to check that levels and codes are consistent and valid. |
A pandas.MultiIndex object.
import pandas as pd
index = pd.MultiIndex.from_product(
[["east", "west"], ["sales", "support"]],
names=["region", "team"],
)
df = pd.DataFrame({"headcount": [3, 2, 4, 5]}, index=index)
print(df.loc["east"])
Creates a two-level index from every region-team combination, then selects one outer-level label.
A DataFrame needs labels such as region and team on its rows.
A complete set of combinations must be materialized as index labels.
Data must be selected using nested keys on one axis.
A MultiIndex is a hierarchical index whose labels have multiple levels. It can be viewed as an array of unique tuples, so a single axis can represent combinations such as region and team.
Follow-up: How can you construct one without manually supplying levels and codes? Use class methods such as from_arrays, from_tuples, from_product, or from_frame.
The levels argument contains the unique labels for each level. The codes argument contains integer arrays that identify which label from each level is used at every position.
Follow-up: Why are codes integers rather than labels? They provide positional references into the unique label arrays stored in levels.
from_product creates a MultiIndex containing all combinations from the supplied iterables. It is useful when the index should cover a complete Cartesian product of level values.
Follow-up: What constraint applies to each iterable? Each iterable must contain unique labels for its level.
MultiIndex.from_arraysMultiIndex.from_tuplesMultiIndex.from_productMultiIndex.from_frameIndexSeriesDataFrame