10000 BUG: DataFrame.sort_index broken if not both lexsorted and monotonic in levels by jreback · Pull Request #15694 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

BUG: DataFrame.sort_index broken if not both lexsorted and monotonic in levels #15694

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

Closed
wants to merge 11 commits into from
Closed
Prev Previous commit
Next Next commit
add doc example
  • Loading branch information
jreback committed Apr 7, 2017
commit 48249ab50aa0dcd160293f99874b87e2769f60dd
11 changes: 7 additions & 4 deletions doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ Other Enhancements
- ``pandas.io.json.json_normalize()`` has gained a ``sep`` option that accepts ``str`` to separate joined fields; the default is ".", which is backward compatible. (:issue:`14883`)
- ``pd.read_csv()`` will now raise a ``csv.Error`` error whenever an end-of-file character is encountered in the middle of a data row (:issue:`15913`)
- A new function has been added to a ``MultiIndex`` to facilitate :ref:`Removing Unused Levels <advanced.shown_levels>`. (:issue:`15694`)
- :func:`MultiIndex.remove_unused_levels` has been added to facilitate :ref:`removing unused levels <advanced.shown_levels>`. (:issue:`15694`)


.. _ISO 8601 duration: https://en.wikipedia.org/wiki/ISO_8601#Durations
Expand Down Expand Up @@ -746,12 +747,14 @@ Sorting works as expected
df.sort_index().index.is_lexsorted()
df.sort_index().index.is_monotonic

However, this example, which has a monotonic level, doesn't behave as desired.
However, this example, which has a non-monotonic 2nd level,
doesn't behave as desired.

.. ipython:: python
df = pd.DataFrame({'value': [1, 2, 3, 4]},
index=pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]]))
df = pd.DataFrame(
{'value': [1, 2, 3, 4]},
index=pd.MultiIndex(levels=[['a', 'b'], ['bb', 'aa']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]]))

Previous Behavior:

Expand Down
17 changes: 17 additions & 0 deletions pandas/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1235,6 +1235,23 @@ def remove_unused_levels(self):
-------
MultiIndex

Examples
--------
>>> i = MultiIndex.from_product([range(2), list('ab')])
MultiIndex(levels=[[0, 1], ['a', 'b']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]])


>>> i[2:]
MultiIndex(levels=[[0, 1], ['a', 'b']],
labels=[[1, 1], [0, 1]])

# the 0 from the first level is not represented
# and can be removed
>>> i[2:].remove_unused_levels()
MultiIndex(levels=[[1], ['a', 'b']],
labels=[[0, 0], [0, 1]])

"""

new_levels = []
Expand Down
0