pandas.MultiIndex.get_level_values#

MultiIndex.get_level_values(level)[source]#

Return vector of label values for requested level.

Length of returned vector is equal to the length of the index.

Parameters:
levelint 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).

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='object', name='level_1')
>>> mi.get_level_values("level_2")
Index(['d', 'e', 'f'], dtype='object', 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')