Skip to content

Commit

Permalink
DOC/TST: Add examples to MultiIndex.get_level_values + related changes (
Browse files Browse the repository at this point in the history
  • Loading branch information
topper-123 authored and gfyoung committed Sep 6, 2017
1 parent 84a39f9 commit d457791
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 4 deletions.
12 changes: 10 additions & 2 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2529,15 +2529,23 @@ def set_value(self, arr, key, value):
def _get_level_values(self, level):
"""
Return an Index of values for requested level, equal to the length
of the index
of the index.
Parameters
----------
level : int
level : int or str
``level`` is either the integer position of the level in the
MultiIndex, or the name of the level.
Returns
-------
values : Index
``self``, as there is only one level in the Index.
See also
---------
pandas.MultiIndex.get_level_values : get values for a level of a
MultiIndex
"""

self._validate_index_level(level)
Expand Down
23 changes: 21 additions & 2 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,15 +882,34 @@ def _get_level_values(self, level):
def get_level_values(self, level):
"""
Return vector of label values for requested level,
equal to the length of the index
equal to the length of the index.
Parameters
----------
level : int or level name
level : int or str
``level`` is either the integer position of the level in the
MultiIndex, or the name of the level.
Returns
-------
values : Index
``values`` is a level of this MultiIndex converted to
a single :class:`Index` (or subclass thereof).
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')
"""
level = self._get_level_number(level)
values = self._get_level_values(level)
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1438,6 +1438,12 @@ def test_get_level_values(self):
result = self.strIndex.get_level_values(0)
tm.assert_index_equal(result, self.strIndex)

# test for name (GH 17414)
index_with_name = self.strIndex.copy()
index_with_name.name = 'a'
result = index_with_name.get_level_values('a')
tm.assert_index_equal(result, index_with_name)

def test_slice_keep_name(self):
idx = Index(['a', 'b'], name='asdf')
assert idx.name == idx[1:].name
Expand Down

0 comments on commit d457791

Please sign in to comment.