Skip to content

Commit c6dec63

Browse files
committed
BUG: fix error for reset_index() with index.name in MultiIndex columns
closes #16120
1 parent 6ad32d2 commit c6dec63

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

doc/source/whatsnew/v0.20.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1623,6 +1623,7 @@ Indexing
16231623
- Bug in ``Series.iloc`` where a ``Categorical`` object for list-like indexes input was returned, where a ``Series`` was expected. (:issue:`14580`)
16241624
- Bug in ``DataFrame.isin`` comparing datetimelike to empty frame (:issue:`15473`)
16251625
- Bug in ``.reset_index()`` when an all ``NaN`` level of a ``MultiIndex`` would fail (:issue:`6322`)
1626+
- Bug in ``.reset_index()`` when raising error for index name already present in ``MultiIndex`` columns (:issue:`16120`)
16261627
- Bug in creating a ``MultiIndex`` with tuples and not passing a list of names; this will now raise ``ValueError`` (:issue:`15110`)
16271628
- Bug in the HTML display with with a ``MultiIndex`` and truncation (:issue:`14882`)
16281629
- Bug in the display of ``.info()`` where a qualifier (+) would always be displayed with a ``MultiIndex`` that contains only non-strings (:issue:`15245`)

pandas/core/internals.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3807,7 +3807,7 @@ def insert(self, loc, item, value, allow_duplicates=False):
38073807
"""
38083808
if not allow_duplicates and item in self.items:
38093809
# Should this be a different kind of error??
3810-
raise ValueError('cannot insert %s, already exists' % item)
3810+
raise ValueError('cannot insert {}, already exists'.format(item))
38113811

38123812
if not isinstance(loc, int):
38133813
raise TypeError("loc must be int")

pandas/tests/test_multilevel.py

+16
Original file line numberDiff line numberDiff line change
@@ -2235,6 +2235,22 @@ def test_reset_index_period(self):
22352235
}, columns=['month', 'feature', 'a'])
22362236
tm.assert_frame_equal(df.reset_index(), expected)
22372237

2238+
def test_reset_index_multiindex_columns(self):
2239+
levels = [['A', ''], ['B', 'b']]
2240+
df = pd.DataFrame([[0, 2], [1, 3]],
2241+
columns=pd.MultiIndex.from_tuples(levels))
2242+
expected = df.copy()
2243+
df.index.name = 'A'
2244+
result = df[['B']].reset_index()
2245+
tm.assert_frame_equal(result, expected)
2246+
2247+
# GH 16120
2248+
# already existing column
2249+
with tm.assertRaisesRegexp(ValueError,
2250+
("cannot insert \('A', ''\), "
2251+
"already exists")):
2252+
df.reset_index()
2253+
22382254
def test_set_index_period(self):
22392255
# GH 6631
22402256
df = DataFrame(np.random.random(6))

0 commit comments

Comments
 (0)