Skip to content
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

Add to_flat_index method to MultiIndex #22866

Merged
merged 16 commits into from
Nov 13, 2018
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1725,6 +1725,7 @@ MultiIndex Components
MultiIndex.set_levels
MultiIndex.set_labels
MultiIndex.to_hierarchical
MultiIndex.to_index
MultiIndex.to_frame
MultiIndex.is_lexsorted
MultiIndex.sortlevel
Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ Other Enhancements
- Compatibility with Matplotlib 3.0 (:issue:`22790`).
- Added :meth:`Interval.overlaps`, :meth:`IntervalArray.overlaps`, and :meth:`IntervalIndex.overlaps` for determining overlaps between interval-like objects (:issue:`21998`)
- :meth:`Timestamp.tz_localize`, :meth:`DatetimeIndex.tz_localize`, and :meth:`Series.tz_localize` have gained the ``nonexistent`` argument for alternative handling of nonexistent times. See :ref:`timeseries.timezone_nonexsistent` (:issue:`8917`)
- :meth:`MultiIndex.to_index` has been added to flatten multiple levels into a single-level :class:`Index` object.

.. _whatsnew_0240.api_breaking:

Expand Down
46 changes: 46 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,52 @@ def _format_attrs(self):
"""
return format_object_attrs(self)

def to_index(self, sep=None):
"""
Convert a MultiIndex to an Index of Tuples containing the level values.

.. versionadded:: 0.24.0

Parameters
----------
sep : str, optional
Not yet implemented.

Returns
-------
pd.Index : an Index with the MultiIndex data represented in Tuples.

Notes
-----
This method will simply return the caller if called by anything other
than a MultiIndex.

See Also
--------
to_series : Similar method to construct a Series.
to_frame : Similar method to construct a DataFrame.

Examples
--------
>>> index = pd.MultiIndex.from_product(
... [['foo', 'bar'], ['baz', 'qux']],
... names=['a', 'b'])
>>> index.to_index()
Index([('foo', 'baz'), ('foo', 'qux'),
('bar', 'baz'), ('bar', 'qux')],
dtype='object')
"""
if sep is not None:
# TODO: Add support for separator to return strs instad of tuples
raise NotImplementedError

if not isinstance(self, ABCMultiIndex):
Copy link
Contributor

Choose a reason for hiding this comment

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

Idle style question (no need to change here): what are people's preferences on

  1. Defining a method for both Index and MultiIndex here, but using an isnstance to figure out which one we're working with
  2. Defining a default implementation here that's return self, and overriding in MultiIndex, so no if isintance?

Copy link
Member

Choose a reason for hiding this comment

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

Preference for 2, and in general, for leaving the base Index class unaware (every time it is possible/reasonable) of the existence and specificities of Index subclasses.

return self

idx = Index(self.values, tupleize_cols=False)
TomAugspurger marked this conversation as resolved.
Show resolved Hide resolved

return idx

def to_series(self, index=None, name=None):
"""
Create a Series with both index and values equal to the index keys
Expand Down
1 change: 1 addition & 0 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ class MultiIndex(Index):
set_levels
set_labels
to_frame
to_index
is_lexsorted
sortlevel
droplevel
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/indexes/multi/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,11 @@ def test_to_series_with_arguments(idx):
assert s.values is not idx.values
assert s.index is not idx
assert s.name != idx.name


def test_to_index(idx):
expected = pd.Index((('foo', 'one'), ('foo', 'two'), ('bar', 'one'),
('baz', 'two'), ('qux', 'one'), ('qux', 'two')),
tupleize_cols=False)
result = idx.to_index()
tm.assert_index_equal(result, expected)
12 changes: 12 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2201,6 +2201,18 @@ def test_tab_complete_warning(self, ip):
with provisionalcompleter('ignore'):
list(ip.Completer.completions('idx.', 4))

def test_to_index(self, indices):
# 22866
if isinstance(indices, MultiIndex):
pytest.skip("Separate expectation for MultiIndex")

result = indices.to_index()
tm.assert_index_equal(result, indices)

def test_to_index_sep_raises(self, indices):
with pytest.raises(NotImplementedError):
indices.to_index(sep="")


class TestMixedIntIndex(Base):
# Mostly the tests from common.py for which the results differ
Expand Down