diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index 3f510ce3d44c0..eb5703990546c 100644 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -132,3 +132,5 @@ Bug Fixes - Bug in unequal comparisons between a ``Series`` of dtype `"category"` and a scalar (e.g. ``Series(Categorical(list("abc"), categories=list("cba"), ordered=True)) > "b"``, which wouldn't use the order of the categories but use the lexicographical order. (:issue:`9848`) - Bug in unequal comparisons between categorical data and a scalar, which was not in the categories (e.g. ``Series(Categorical(list("abc"), ordered=True)) > "d"``. This returned ``False`` for all elements, but now raises a ``TypeError``. Equality comparisons also now return ``False`` for ``==`` and ``True`` for ``!=``. (:issue:`9848`) + +- Bug in ``MultiIndex.sortlevel()`` results in unicode level name breaks (:issue:`9875`) diff --git a/pandas/core/index.py b/pandas/core/index.py index fd11cd7f598c3..cd861cf26c892 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -4023,7 +4023,7 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True): labels = list(self.labels) shape = list(self.levshape) - if isinstance(level, (str, int)): + if isinstance(level, (compat.string_types, int)): level = [level] level = [self._get_level_number(lev) for lev in level] diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py index 6ea76710b4de7..14178f99d6313 100644 --- a/pandas/tests/test_frame.py +++ b/pandas/tests/test_frame.py @@ -16,7 +16,7 @@ from pandas.compat import( map, zip, range, long, lrange, lmap, lzip, - OrderedDict, u, StringIO + OrderedDict, u, StringIO, string_types ) from pandas import compat @@ -12428,6 +12428,30 @@ def test_unstack_bool(self): ['c', 'l']])) assert_frame_equal(rs, xp) + def test_unstack_level_binding(self): + # GH9856 + mi = pd.MultiIndex( + levels=[[u'foo', u'bar'], [u'one', u'two'], [u'a', u'b']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 0]], + names=[u'first', u'second', u'third']) + s = pd.Series(0, index=mi) + result = s.unstack([1, 2]).stack(0) + + expected_mi = pd.MultiIndex( + levels=[['foo', 'bar'], ['one', 'two']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=['first', 'second']) + + expected = pd.DataFrame(np.array([[np.nan, 0], + [0, np.nan], + [np.nan, 0], + [0, np.nan]], + dtype=np.float64), + index=expected_mi, + columns=pd.Index(['a', 'b'], name='third')) + + self.assert_frame_equal(result, expected) + def test_unstack_to_series(self): # check reversibility data = self.frame.unstack()