diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index 945922b5f9ba8..c07760a94d3f1 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -1623,6 +1623,7 @@ Indexing - Bug in ``Series.iloc`` where a ``Categorical`` object for list-like indexes input was returned, where a ``Series`` was expected. (:issue:`14580`) - Bug in ``DataFrame.isin`` comparing datetimelike to empty frame (:issue:`15473`) - Bug in ``.reset_index()`` when an all ``NaN`` level of a ``MultiIndex`` would fail (:issue:`6322`) +- Bug in ``.reset_index()`` when raising error for index name already present in ``MultiIndex`` columns (:issue:`16120`) - Bug in creating a ``MultiIndex`` with tuples and not passing a list of names; this will now raise ``ValueError`` (:issue:`15110`) - Bug in the HTML display with with a ``MultiIndex`` and truncation (:issue:`14882`) - Bug in the display of ``.info()`` where a qualifier (+) would always be displayed with a ``MultiIndex`` that contains only non-strings (:issue:`15245`) diff --git a/pandas/core/internals.py b/pandas/core/internals.py index f265f5f438280..840206977cf30 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3807,7 +3807,7 @@ def insert(self, loc, item, value, allow_duplicates=False): """ if not allow_duplicates and item in self.items: # Should this be a different kind of error?? - raise ValueError('cannot insert %s, already exists' % item) + raise ValueError('cannot insert {}, already exists'.format(item)) if not isinstance(loc, int): raise TypeError("loc must be int") diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 173ac97691b3b..e81e6e2d987c6 100755 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -2235,6 +2235,22 @@ def test_reset_index_period(self): }, columns=['month', 'feature', 'a']) tm.assert_frame_equal(df.reset_index(), expected) + def test_reset_index_multiindex_columns(self): + levels = [['A', ''], ['B', 'b']] + df = pd.DataFrame([[0, 2], [1, 3]], + columns=pd.MultiIndex.from_tuples(levels)) + expected = df.copy() + df.index.name = 'A' + result = df[['B']].reset_index() + tm.assert_frame_equal(result, expected) + + # GH 16120 + # already existing column + with tm.assertRaisesRegexp(ValueError, + ("cannot insert \('A', ''\), " + "already exists")): + df.reset_index() + def test_set_index_period(self): # GH 6631 df = DataFrame(np.random.random(6))