Skip to content

BUG: Fix bug where sort_index if unsorted levels. #12342

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 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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/whatsnew/v0.18.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -992,3 +992,4 @@ Bug Fixes
- Bug in ``crosstab`` where arguments with non-overlapping indexes would return a ``KeyError`` (:issue:`10291`)

- Bug in ``DataFrame.apply`` in which reduction was not being prevented for cases in which ``dtype`` was not a numpy dtype (:issue:`12244`)
- Bug in ``MultiIndex.sort_index`` where if the levels were out of order, but the labels were monotonic, then the index would return unsorted. (:issue:`12261`)
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3236,7 +3236,7 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False,

# make sure that the axis is lexsorted to start
# if not we need to reconstruct to get the correct indexer
if not labels.is_lexsorted():
if not labels.is_lexsorted() or not all([labels.get_level_values(i).is_monotonic for i in range(labels.nlevels)]):
labels = MultiIndex.from_tuples(labels.values)

indexer = _lexsort_indexer(labels.labels, orders=ascending,
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/frame/test_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,18 @@ def test_frame_column_inplace_sort_exception(self):

cp = s.copy()
cp.sort_values() # it works!

def test_sort_added_index(self):
# GH 12261
df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []]))

df.loc['b', '2'] = 1
df.loc['a', '3'] = 1

expected = DataFrame([[1.0, np.nan], [np.nan, 1.0]],
index=MultiIndex.from_product([['b', 'a'], ['']]),
columns=['2', '3']).sort_index()

actual = df.sort_index()

assert_frame_equal(expected, actual)