Skip to main content
`Ctrl`+`K`

# pandas.MultiIndex.get_level_values

MultiIndex.get_level_values(level)

  Return vector of label values for requested level.

  Length of returned vector is equal to the length of the index. The get_level_values method is a crucial utility for extracting specific level values from a MultiIndex. This function is particularly useful when working with multi-level data, allowing you to isolate and manipulate individual levels without having to deal with the complexity of the entire MultiIndex structure. It seamlessly handles both integer and string-based level access, providing flexibility in how you can interact with the data. Additionally, this method ensures that the returned Index maintains the integrity of the original data, even when missing values are present, by appropriately casting the result to a suitable data type.

  Parameters:
    level int or str

      `level` is either the integer position of the level in the MultiIndex, or the name of the level.

  Returns:
    Index

      Values is a level of this MultiIndex converted to a single `Index` (or subclass thereof).

  See also

  `MultiIndex`

    A multi-level, or hierarchical, index object for pandas objects.

  `Index`

    Immutable sequence used for indexing and alignment.

  `MultiIndex.remove_unused_levels`

    Create new MultiIndex from current that removes unused levels.

  Notes

  If the level contains missing values, the result may be casted to `float` with missing values specified as `NaN`. This is because the level is converted to a regular `Index`.

  Examples

  Create a MultiIndex:

      >>> mi = pd.MultiIndex.from_arrays((list("abc"), list("def")))
      >>> mi.names = ["level_1", "level_2"]

  Get level values by supplying level as either integer or name:

      >>> mi.get_level_values(0)
      Index(['a', 'b', 'c'], dtype='str', name='level_1')
      >>> mi.get_level_values("level_2")
      Index(['d', 'e', 'f'], dtype='str', name='level_2')

  If a level contains missing values, the return type of the level may be cast to `float`.

      >>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).dtypes
      level_0    int64
      level_1    int64
      dtype: object
      >>> pd.MultiIndex.from_arrays([[1, None, 2], [3, 4, 5]]).get_level_values(0)
      Index([1.0, nan, 2.0], dtype='float64')