Skip to content

DOC: Edit MultiIndex.set_levels() docstring to clarify that set_levels() interprets passed values as new components of the .levels attribute (#28294) #29143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
28 changes: 21 additions & 7 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,32 +757,46 @@ def set_levels(self, levels, level=None, inplace=False, verify_integrity=True):
Examples
--------
>>> idx = pd.MultiIndex.from_tuples([(1, 'one'), (1, 'two'),
(2, 'one'), (2, 'two')],
(2, 'one'), (2, 'two'),
(3, 'one'), (3, 'two')],
names=['foo', 'bar'])
>>> idx.set_levels([['a', 'b'], [1, 2]])
>>> idx.set_levels([['a', 'b', 'c'], [1, 2]])
MultiIndex([('a', 1),
('a', 2),
('b', 1),
('b', 2)],
('b', 2),
('c', 1),
('c', 2)],
names=['foo', 'bar'])
>>> idx.set_levels(['a', 'b'], level=0)
>>> idx.set_levels(['a', 'b', 'c'], level=0)
MultiIndex([('a', 'one'),
('a', 'two'),
('b', 'one'),
('b', 'two')],
('b', 'two'),
('c', 'one'),
('c', 'two')],
names=['foo', 'bar'])
>>> idx.set_levels(['a', 'b'], level='bar')
MultiIndex([(1, 'a'),
(1, 'b'),
(2, 'a'),
(2, 'b')],
(2, 'b'),
(3, 'a'),
(3, 'b')],
names=['foo', 'bar'])
>>> idx.set_levels([['a', 'b'], [1, 2]], level=[0, 1])

If any of the levels passed to ``set_levels()`` exceeds the
existing length, all of the values from that argument will
be stored though truncated in the MultiIndex output.
Copy link
Member

@gfyoung gfyoung Nov 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This wording ("stored though truncated") is a little awkward - not sure I 100% understand what this means

Copy link
Contributor Author

@hweecat hweecat Nov 10, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would the following wording be clearer in expressing the concept?

"stored in the MultiIndex levels, though the values will be truncated in the MultiIndex output."

Feel free to let me know what you think.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that’s a great edit - care to make that change?


>>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1])
MultiIndex([('a', 1),
('a', 2),
('b', 1),
('b', 2)],
names=['foo', 'bar'])
>>> idx.set_levels([['a', 'b', 'c'], [1, 2, 3, 4]], level=[0, 1]).levels
FrozenList([['a', 'b', 'c'], [1, 2, 3, 4]])
"""
if is_list_like(levels) and not isinstance(levels, Index):
levels = list(levels)
Expand Down